Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if a char is a newline

Tags:

c++

I'm doing an exercise in C++ Primer and basically I am using a switch statement to count the number of vowels in a text that I input.

I input the text using a while loop.

while(cin >> ch)

and proceed with the cases, a, e, i, o, u, incrementing an integer variable for the respective cases. Now the next part of the question says also count the spaces, tabs and newlines.

I tried doing

case ' ':

and so forth using '\t' and '\n'. But it seems like it doesn't compute these cases. I also tried just using a default and using an if else statement

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

etc. But this doesn't proceed either. I also tried putting in the integer values of ' ', '\t', '\n'. What am I doing wrong here? Also, I know that if I use isspace() I can count the combined total but I need to compute each one individually. I'm not sure why the equality test won't do the job.

like image 341
Mars Avatar asked Aug 25 '13 04:08

Mars


People also ask

Is newline a character C?

In programming languages, such as C, Java, and Perl, the newline character is represented as a '\n' which is an escape sequence.

How do you find a new line in Java?

In Windows, a new line is denoted using “\r\n”, sometimes called a Carriage Return and Line Feed, or CRLF. Adding a new line in Java is as simple as including “\n” , “\r”, or “\r\n” at the end of our string.

How do you show a new line in a string in python?

In Python, the new line character “\n” is used to create a new line. When inserted in a string all the characters after the character are added to a new line. Essentially the occurrence of the “\n” indicates that the line ends here and the remaining characters would be displayed in a new line.


1 Answers

By default, formatted input from streams skips leading whitespace. You need to either disable skipping of leading whitespaces or use one of the functions which won't skip spaces:

std::cin >> std::noskipws; // disables skipping of leading whitespace
char c;
while (std::cin.get(c)) {  // doesn't skip whitespace anyway
   ...
}
like image 86
Dietmar Kühl Avatar answered Sep 20 '22 23:09

Dietmar Kühl