读取空行C++
Read empty lines C++
我在读取和区分输入中的空行时遇到问题。
以下是示例输入:
number
string
string
string
...
number
string
string
...
每个数字表示输入的开始,字符串序列后的空行表示输入的结束。字符串可以是一个短语,而不仅仅是一个单词。
我的代码执行以下操作:
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
}
}
我直接尝试过cin>>空白,但没有用。
有人能帮我解决这个问题吗?
谢谢!
在您读取带有此行的数字后:
while(cin >> n) { //number
cin
在最后一位之后不读取任何内容。这意味着cin的输入缓冲区仍然包含数字所在行的其余部分。因此,您需要跳过这一行,和下一个空行。只需使用getline两次就可以做到这一点。即
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
}
}
相关文章:
- 理解boost::asio-async_read在无需读取内容时的行为
- 使用新行和不使用新行读取文件
- 读取文件并输入到矢量中
- 用c++从输入文件中读取另一行
- 读取文件的最后一行并输入到链接列表时出错
- 在进程中对同一管道进行读取和写入时C++管道出现问题
- 无法找到/读取配置文件.conf-FileIOException
- 如何使用Luacneneneba API正确读取字符串和表参数
- C++将文本文件中的数据读取到结构数组中
- 正在将csv文件读取为双精度矢量
- 为什么 sscanf 无法从一个字符串中读取uint64_t和字符?
- 为什么在读取文件大小时文件IO速度会发生变化
- 正在读取二进制文件(is_open)
- 如何在c++中从文本文件中逐行读取整数
- SSH通过/sbin/SSH无法读取RSA密钥文件(从控制台运行)
- 独立读取-修改-写入顺序
- 从文本文件中读取时钟时间和事件时间并进行处理
- 如何从文本文件中读取值和数组
- 为什么文件名被设置为一个点,而不是在读取矢量中的文件名时
- 一种在C++中读取TXT配置文件的简单方法