[英]Ifstream.getline() - Only reading first line?
I'm just trying to run a simple c++ program that will format a .txt
file with data entries. 我只是想运行一个简单的c ++程序,它将使用数据条目格式化
.txt
文件。 I have run it with many different text files of the exact same format, and now it just won't work. 我已经使用完全相同格式的许多不同文本文件运行它,现在它将无法正常工作。 I'm sure the solution is simple.
我确信解决方案很简单。
Here is a simplified version of the program (I trimmed down everything to only show the parts that are giving me trouble). 这是该程序的简化版本(我修剪了所有内容,只显示给我带来麻烦的部分)。
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <iomanip>
using namespace std;
int main(){
ifstream filei("in.txt");
ofstream fileo("comlab.txt");
double a, b;
string s;
stringstream ss;
while (getline(filei,s)){
ss<<s;
ss>>a>>b;
fileo<<setw(10)<<a<<setw(10)<<b<<'\n';
}
fileo.close();
}
Here is a sample input for in.txt
: 以下是
in.txt
的示例输入:
1 11
2 22
3 33
4 44
5 55
Now here is what I want to show up (exactly the same as input): 现在这是我想要显示的内容(与输入完全相同):
1 11
2 22
3 33
4 44
5 55
But here is what actually shows up: 但这是实际显示的内容:
1 11
1 11
1 11
1 11
1 11
What is going on? 到底是怎么回事? I'm compiling with g++ and following the C++11 standard.
我正在使用g ++编译并遵循C ++ 11标准。
When you execute 当你执行
ss>>a>>b;
in the first round of execution of the loop. 在第一轮循环执行中。
ss
is already at the end of the stream. ss
已经在流的末尾了。 ie ss.eof() == true
. 即
ss.eof() == true
。 You need to clear its state and reset state to start reading from the beginning. 您需要清除其状态并重置状态以从头开始读取。
while (getline(filei,s)){
ss<<s;
ss>>a>>b;
ss.clear();
ss.seakg(0);
fileo<<setw(10)<<a<<setw(10)<<b<<'\n';
}
A better alternative is to create the object within the scope of the loop. 更好的选择是在循环范围内创建对象。
while (getline(filei,s)){
stringstream ss;
ss<<s;
ss>>a>>b;
fileo<<setw(10)<<a<<setw(10)<<b<<'\n';
}
or even simpler (Thanks to @vsoftco for the suggestion) 甚至更简单(感谢@vsoftco的建议)
while (getline(filei,s)){
stringstream ss(s);
ss>>a>>b;
fileo<<setw(10)<<a<<setw(10)<<b<<'\n';
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.