How to detect empty lines while reading from istream object in C++?(c++ - 从C++中的istream对象读取时如何检测空行?)
问题描述
如何检测一行是否为空?
How can I detect if a line is empty?
我有:
1
2
3
4
5
我正在用 istream r 阅读这篇文章所以:
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 but this detects the that goes after number 1 . The translation of the above input is: 1 2 3 4 5 if I'm correct...
因为我要操作整数,所以我宁愿将它们读为整数而不是使用 getline 然后转换为整数...
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
2
3
4
5
");
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++ - 从C++中的istream对象读取时如何检测空行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:c++ - 从C++中的istream对象读取时如何检测空行?
基础教程推荐
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- CString 到 char* 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
