C++: Why does space always terminate a string when

2020-07-10 09:55发布

问题:

Using type std::string to accept a sentence, for practice (I haven't worked with strings in C++ much) I'm checking if a character is a vowel or not. I got this:

for(i = 0; i <= analyse.length(); i++) {
if(analyse[i] == 'a' || analyse[i] == 'e' [..etc..]) {
 ...vowels++;    
} else { ...
 ...consonants++;
}

This works fine if the string is all one word, but the second I add a space (IE: aeio aatest) it will only count the first block and count the space as a consonant, and quit reading the sentence (exiting the for loop or something).

Does a space count as no character == null? Or some oddity with std::string?, It would be helpful to know why that is happening!

EDIT: I'm simply accepting the string through std::cin, such as:

std::string analyse = "";
std::cin >> analyse;

回答1:

I'd guess you're reading your string with something like your_stream >> your_string;. Operator >> for strings is defined to work (about) the same as scanf's %s conversion, which reads up until it encounters whitespace -- therefore, operator>> does the same.

You can read an entire line of input instead with std::getline. You might also want to look at an answer I posted to a previous question (provides some alternatives to std::getline).



回答2:

I can't tell from the code that you have pasted, but I'm going to go out on a limb and guess that you're reading into the string using the stream extraction operator (stream >> string).

The stream extraction operator stops when it encounters whitespace.

If this isn't what's going on, can you show us how you're populating your string, and what its contents are?

If I'm right, then you're going to want a different method of reading content into the string. std::getline() is probably the easiest method of reading from a file. It stops at newlines instead of at whitespace.


Edit based on edited question: use this (doublecheck the syntax. I'm not in front of my compiler.):

std::getline(std::cin, analyze); 

This ought to stop reading when you press "enter".



回答3:

If you want to read in an entire line (including the blanks) then you should read using getline. Schematically it looks like this:

#include <string>
istream& std::getline( istream& is, string& s );

To read the whole line you do something like this:

string s;
getline( cin, s );
cout << "You entered " << s << endl;

PS: the word is "consonant", not "consenent".



回答4:

The >> operator on an istream separates strings on whitespace. If you want to get a whole line, you can use readline(cin,destination_string).



标签: c++ string std