Katie Stevers Katie Stevers - 4 years ago 94
C++ Question

How to use string with phrases that contain spaces

I used cin.getline after cin.ignore() but I am getting an error saying unassigned int... Not sure what to do or what is wrong. Any suggestions?

Here is my code:

#include <iostream>
#include <string>
#include <cstring>

using namespace std;


int main()
{
string phras;
cout << " Provide a phrase, up to 30 characters with spaces > " << endl;
cin.ignore();
cin.getline(phras, sizeof(phras));
cout << " The phrase is: " << phras << endl;
cout << endl;


return 0;
}


UPDATE
I changed cin.getline(phras, sizeof(phras));
to getline(cin,phras)
Problem solved! Thanks for the help everyone!

Answer Source

The problem is that

char letter[1];

isn't large enough. If a C string is to hold up to N characters, it needs to be declared char letter[N+1] to allow room for the null terminator character. So if the user is going to type a single character, it needs to be:

char letter[2];

As a result, you're getting undefined behavior when cin >> letter writes 2 characters into the array that only has room for 1.

Similarly, if the user is allowed to type a 10-letter word, it should be:

char word[11];

and it should be:

char phrase[31];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download