Check if char is a newline

I am doing an exercise in C ++ Primer, and basically I use the switch statement to count the number of vowels in the text that I entered.

I enter text using a while loop.

while(cin >> ch) 

and proceed to the cases a, e, i, o, u, increasing the integer variable for the corresponding cases. Now, the next part of the question also indicates spaces, tabs, and newlines.

I tried to do

 case ' ': 

etc. using '\ t' and '\ n'. But it does not seem to be calculating these cases. I also tried using the default and using the if else statement

 default: if(ch == ' ') ++space; 

etc .. But this does not happen. I also tried to enter the integer values ​​'', '\ t', '\ n'. What am I doing wrong here? In addition, I know that if I use isspace (), I can calculate the total, but I need to calculate each separately. I am not sure why the equality test will not do the job.

+6
source share
2 answers

By default, formatted input from streams skips leading spaces. You need to either disable skipping leading spaces, or use one of the functions that will not skip spaces:

 std::cin >> std::noskipws; // disables skipping of leading whitespace char c; while (std::cin.get(c)) { // doesn't skip whitespace anyway ... } 
+12
source

As Dietmar said, spaces are skipped by default. You can use cin.getline () to provide your own line separator instead of space characters. I would say that this is usually an easier way to read input than using cin.get() .

+1
source

Source: https://habr.com/ru/post/952442/


All Articles