Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect empty lines while reading from istream object in C++?

How can I detect if a line is empty?

I have:

1
2
3
4

5

I'm reading this with istream r so:

int n;
r >> n

I want to know when I reach the space between 4 and 5. I tried reading as char and using .peek() to detect \n but this detects the \n that goes after number 1 . The translation of the above input is: 1\n2\n3\n4\n\n5\n if I'm correct...

Since I'm going to manipulate the ints I rather read them as ints than using getline and then converting to int...

like image 665
bb2 Avatar asked Feb 10 '12 21:02

bb2


People also ask

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

So to check if you have encountered (or read) an empty-line, you simply need to check if the contents of line is '\n' . To get the first character in line all you need do is dereference it, e.g. *line and compare the first character against the '\n' character, e.g.

Does Getline get empty lines?

The reason is that getline() reads till enter is encountered even if no characters are read. So even if there is nothing in the third line, getline() considers it as a single line. Further, observe the problem in the second line. The code can be modified to exclude such blank lines.

How do I print an empty line in C++?

As a programmer, you can use endl or \n to create new line commands in C++.


2 Answers

It could look like this:

#include <iostream>
#include <sstream>
using namespace std;

int main()
{
    istringstream is("1\n2\n3\n4\n\n5\n");
    string s;
    while (getline(is, s))
    {
        if (s.empty())
        {
            cout << "Empty line." << endl;
        }
        else
        {
            istringstream tmp(s);
            int n;
            tmp >> n;
            cout << n << ' ';
        }
    }
    cout << "Done." << endl;
    return 0;
}

output:

1 2 3 4 Empty line.
5 Done.

Hope this helps.

like image 114
LihO Avatar answered Sep 25 '22 18:09

LihO


If you really don't want using getline, this code works.

#include <iostream>
using namespace std;


int main()
{
    int x;
    while (!cin.eof())
    {
        cin >> x;
        cout << "Number: " << x << endl;

        char c1 = cin.get();
        char c2 = cin.peek();

        if (c2 == '\n')
        {
            cout << "There is a line" << endl;
        }
    }
}

But be aware that this is not portable. When you using system that has different end lines characters than '\n' then would be problem. Consider reading whole lines and then extract data from it.

like image 21
gumik Avatar answered Sep 23 '22 18:09

gumik