Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read empty lines C++

Tags:

c++

input

I am having trouble reading and differentiating empty lines from an input.

Here's the sample input:

 number

 string
 string
 string
 ...

 number

 string
 string
 ...

Each number represents the start of an input and the blank line after the sequence of strings represents the end of an input. The string can be a phrase, not only one word.

My code does the following:

  int n;

  while(cin >> n) { //number

    string s, blank;
    getline(cin, blank); //reads the blank line

    while (getline(cin, s) && s.length() > 0) { //I've tried !s.empty()
        //do stuff
    }
  }

I've tried directly cin >> blank, but it didn't work.

Can someone help me solve this issue?

Thanks!

like image 970
Larissa Leite Avatar asked Sep 01 '14 01:09

Larissa Leite


People also ask

How to read empty line in c?

You can also choose between isblank() which recognizes blanks and tabs, and isspace() which recognizes blanks, tabs, newlines, formfeeds, carriage returns and vertical tabs ( " \t\n\f\r\v" ).

How do you check if a line is empty in a file in C?

Simple. Use fgets. Check the buffer to see if it contains only a newline (or alternately, only whitespace and a newline). Or fgets + sscanf, and see if sscanf returns what you expect.

What does fgets return for empty line?

fgets returns at most nchar characters of the next line. If the number of characters specified by nchar includes characters beyond the newline character or the end-of-file marker, then fgets does not return any characters beyond the new line character or the end-of-file marker.

How does fgets work in C?

fgets() function in CThe function reads a text line or a string from the specified file or console. And then stores it to the respective string variable. Similar to the gets() function, fgets also terminates reading whenever it encounters a newline character.


1 Answers

After you read the number with this line:

while(cin >> n) { //number

cin doesn't read anything after the last digit. That means cin's input buffer still contains the rest of the line that the number was on. So, you need to skip that line, and the next blank line. You could do that by just using getline twice. i.e.

while(cin >> n) { //number

    string s, blank;
    getline(cin, blank); // reads the rest of the line that the number was on
    getline(cin, blank); // reads the blank line

    while (getline(cin, s) && !s.empty()) {
        //do stuff
    }
  }
like image 67
Benjamin Lindley Avatar answered Oct 02 '22 15:10

Benjamin Lindley