pin*_*-na 1 c++ operators ifstream peek end-of-line
我环顾四周,仍然没有找到如何做到这一点,所以,请耐心等待我.
假设我必须读取包含不同类型数据的txt文件,其中第一个浮点数是一个id,然后有一些(不总是相同数量)的其他浮点数代表其他东西...次数,例如, 成对.
所以该文件看起来像:
1 0.2 0.3
2.01 3.4 5.6 5.7
3 2.0 4.7
...
Run Code Online (Sandbox Code Playgroud)
经过大量的研究,我最终得到了这样的函数:
vector<Thing> loadThings(char* filename){
vector<Thing> things;
ifstream file(filename);
if (file.is_open()){
while (true){
float h;
file >> h; // i need to load the first item in the row for every thing
while ( file.peek() != '\n'){
Thing p;
p.id = h;
float f1, f2;
file >> f1 >> f2;
p.ti = f1;
p.tf = f2;
things.push_back(p);
if (file.eof()) break;
}
if (file.eof()) break;
}
file.close();
}
return things;
}
Run Code Online (Sandbox Code Playgroud)
但(file.peek() != '\n')条件的while循环本身永远不会完成,我的意思是......偷看永远不等于'\n'
有谁知道为什么?或者也许用其他方式使用>>运算符读取文件?!非常感谢你!
只是建议另一种方式,为什么不使用
// assuming your file is open
string line;
while(!file.eof())
{
getline(file,line);
// then do what you need to do
}
Run Code Online (Sandbox Code Playgroud)