在C ++中从istream对象读取时如何检测空行? [英] How to detect empty lines while reading from istream object in C++?

查看:145
本文介绍了在C ++中从istream对象读取时如何检测空行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何检测行是否为空?

我有:

1
2
3
4

5

我正在用istream读这个
所以:

I'm reading this with istream r so:

int n;
r >> n

我想知道当我达到4和5之间的空间。
我试过读取为char和使用.peek()来检测\\\
,但这会检测到在数字1之后的\\\
。上面输入的翻译是:1 \\\
2\\\
3\\\
4\\\
\\\
5\\\
如果我是正确的...

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...

因为我要操纵int,我更喜欢阅读它们作为int比使用getline然后转换为int ...

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

推荐答案

它可能如下所示:

#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;
}

输出:

1 2 3 4 Empty line.
5 Done.

希望这有帮助。

这篇关于在C ++中从istream对象读取时如何检测空行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆