我怎样才能读取数据直到行尾?我有一个文本文件"file.txt"
1 5 9 2 59 4 6
2 1 2
3 2 30 1 55
Run Code Online (Sandbox Code Playgroud)
我有这个代码:
ifstream file("file.txt",ios::in);
while(!file.eof())
{
....//my functions(1)
while(?????)//Here i want to write :while (!end of file)
{
...//my functions(2)
}
}
Run Code Online (Sandbox Code Playgroud)
在我的函数中(2)我使用行中的数据,它需要是Int,而不是char
不要使用,while(!file.eof())因为eof()只有在读取文件末尾后才会设置.它并不表示下一次读取将是文件的结尾.您可以while(getline(...))改为使用并结合使用istringstream来读取数字.
#include <fstream>
#include <sstream>
using namespace std;
// ... ...
ifstream file("file.txt",ios::in);
if (file.good())
{
string str;
while(getline(file, str))
{
istringstream ss(str);
int num;
while(ss >> num)
{
// ... you now get a number ...
}
}
}
Run Code Online (Sandbox Code Playgroud)
你需要阅读为什么循环条件中的iostream :: eof被认为是错误的?.
至于阅读直到行尾。有std::getline。
不过,您还有另一个问题,那就是您的循环while (!file.eof())很可能不会按您的预期工作。原因是直到您尝试从文件末尾读取之后eofbit才会设置该标志。相反,你应该这样做,例如。while (std::getline(...))
| 归档时间: |
|
| 查看次数: |
52771 次 |
| 最近记录: |