Reputation: 189
I am working on a project for my programming class that requires me to work with strings. The program begins by asking the user to input a phrase. Normally I would declare something such as:
string phrase;
Then I would use:
getline(cin,phrase);
However, the professor told the class that we aren't allowed to use the string class, we must use only c-based strings. I could be wrong but I believe that c-based strings look something like this:
char phrase[12] = "hello world";
If this is what my professor means by c-based strings, then I do not know how to input a phrase into them. When I attempt this, the program only stores the first word of the phrase and stops at the first space it sees. For example:
char phrase[12];
cin >> phrase;
//input: hello world
cout << phrase;
//output: hello
Any advice would help and would be greatly appreciated, thank you.
Upvotes: 1
Views: 6786
Reputation: 940
If you are reading input into a static char array you can use sizeof(charArray) to determine its maximum lengh. But take into consideration that the last symbol will be end of line, so you can read maximum length-1 symbols into this array.
char phrase[12] ;
cin.getline(phrase, sizeof(phrase));
Upvotes: 1
Reputation: 15847
You need to use cin.getline(var_id, var_length)
and not cin >> var_id
, which actually stops storing the input in the variable when it encounters a space
or a new line
.
If you want to know more about cin.getline
and what problems its use can cause, you can have a look to this post: Program skips cin.getline()
Upvotes: 4