C ++: Why does space always break a line when reading?

Using the std::string type to accept the sentence, for practice (I did not work with strings in C ++), I check if the character is a vowel or not. I got it:

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

This works fine if the line is one word and the second I add a space (IE: aeio aatest ), it will only read the first block and consider the space as consonant, and stop reading the sentence (exit the for loop or something else) .

Is there a space without the == null character? Or some kind of weirdness with std::string ?, It would be useful to know why this is happening!

EDIT: I just accept the string via std :: cin, for example:

 std::string analyse = ""; std::cin >> analyse; 
+6
c ++ string std
source share
4 answers

I would suggest that you read your line with something like your_stream >> your_string; . The >> operator for strings is defined as working (approximately) in the same way as scanf %s conversion, which is read until it encounters spaces, so operator>> does the same.

Instead of std::getline you can read an entire line of input. You can also see the answer that I sent to the previous question (provides some alternatives to std::getline ).

+9
source share

I can’t tell from the code that you inserted, but I'm going to go to a limb and assume that you are reading a string using the stream extraction operator (stream → string).

The stream extraction statement stops when it encounters spaces.

If this is not the case, can you show us how you fill in your line and what is its contents?

If I'm right, then you will need a different method of reading the contents into a string. std :: getline () is probably the easiest way to read from a file. It stops in newlines, not in spaces.


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

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

This should stop when you press enter.

+4
source share

If you want to read the entire line (including spaces), you must read using getline. Schematically, it looks like this:

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

To read the entire line, you do something like this:

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

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

+2
source share

The >> operator on istream separates lines from spaces. If you want to get the whole line, you can use readline(cin,destination_string) .

+1
source share

All Articles