std::getline 读取最后一个字符串两次
std::getline read the last string twice
测试文件写成
Sat Aug 10 22:03:09 2019
Test completed
首先我使用了 in.eof((,但有人告诉我永远不要使用 thoes in.eof((。
enter code here
#include <fstream>
#include <iostream>
#include <string>
int main() {
//test.txt is a test file.
std::ifstream in("test.txt");
if (!in.is_open()) {
std::cout << "file not found" << std::endl;
return 0;
}
std::string s;
while (in) {
getline(in, s);
std::cout << s << std::endl;
}
return 0;
}
我希望结果像
Sat Aug 10 22:03:09 2019
Test completed
但结果是
Sat Aug 10 22:03:09 2019
Test completed
Test completed
问题出在代码的这一部分,就在最后一次成功读取之后:
while (in) { // succeeds
std::getline(in, s); // fails (EOF), and s is unchanged
这完全等同于为什么 iostream::eof 在循环条件中(即while (!stream.eof())
( 被认为是错误的?
解决方法是使getline()
结果成为条件的一部分:
while(std::getline(in, s)) {
做你想做的事的标准方法是
for (std::string s; std::getline(in, s);)
该问题可能与文件末尾的新行符号 (n
( 有关。
在getline
成功时循环,而不是在istream
有效时循环。
while (getline(in, s)) {
std::cout << s << std::endl;
}
相关文章:
- 两个字符串在 c++ 中不相等
- g++的分段错误(在NaN上使用to_string两次时)
- 使用 getline(cin, var) 两次在进行字符串比较时会产生错误 (==)
- 我的字符串数组一次打印出前两个字符串
- std::getline 读取最后一个字符串两次
- 使用字符串流逐行读取文件两次
- *char数组到字符串(两次运行代码和两个不同的结果)
- 阵列不能两次将相同的名称保存,当要添加新字符串时,程序应检查以查看该名称是否已经存在
- Regex_replace两次匹配字符串的结尾
- 为什么必须键入 getline(cin,字符串)两次
- 为什么传入的字符串在打印两次以上时会有所不同
- 静态 c++ 对象中的 JNI 环境指针并调用连续两次使用字符串参数的 Java 函数会使 JVM 崩溃
- 有没有办法将 int 赋入具有递归函数的字符串中,而无需将数字反转两次
- C++:I用不同的位置调用字符串 substr 两次,转换为常量字符 *,它们返回相同的,为什么
- 做..while() 将最后一个字符串重复两次
- 如何从字符串流中的同一位置读取两次
- 我如何一次传递两个字符串
- 一次两个字符串算法
- 出现至少两次的最长子字符串:c++ question
- 在c++中使用boost拆分字符串两次