提问人:Muhammad Arslan Waqar 提问时间:12/25/2021 最后编辑:Vlad from MoscowMuhammad Arslan Waqar 更新时间:12/25/2021 访问量:93
while 循环应该在读取我文件中的第三行后结束,但为什么它会第四次运行?[复制]
The while loop should end after reading the third line in my file but why does it run the fourth time? [duplicate]
问:
void Load_from_file()
{
ifstream fin("Data.txt");
//fin.open("Data.txt");
if (!fin.is_open())
cout << "Error while opening the file" << endl;
else
{
int f_id;
int u_id;
int priority;
char acc_type;
char delim;
while (!fin.eof())
{
fin >> f_id;
fin >> delim; // skipping the comma
fin >> u_id;
fin >> delim;
fin >> priority;
fin >> delim;
fin >> acc_type;
}
fin.close();
}
}
文件中的数据是:
7551,10,3,R
25551,3,10,W
32451,4,7,R
while 循环应该在第三次迭代后结束,但在第四次迭代后终止
答:
1赞
Vlad from Moscow
12/25/2021
#1
问题出在 while 语句中的条件
while (!fin.eof())
{
fin >> f_id;
fin >> delim; // skipping the comma
fin >> u_id;
fin >> delim;
fin >> priority;
fin >> delim;
fin >> acc_type;
}
条件 fin.eof() 可以在读取最后一个数据后出现在 while 循环的主体中。
要么你需要写
while (fin >> f_id >> delim >> u_id >> delim >>
priority >> delim >> acc_type );
或者最好读取一整行,然后使用字符串流输入各种数据,例如
while ( std::getline( fin, line ) )
{
std::istringstream iss( line );
iss >> f_id;
// and so on
}
评论
while (!fin.eof())
while(fin >> f_id >> delim >> u_id >> delim >> priority >> delim >> acc_type) {/*do something with the data...?*/}