我有以下格式。每行有两个整数,文件以“*”结尾。我怎样才能从文件中读取这两个数字。谢谢。
4 5
7 8
78 89
* //end of file
编辑
我知道读取这两个数字但不知道如何处理“*”。如果我将每个数字存储为整数类型并通过 cin
读取它们。但是最后一行是字符串类型。所以问题是我把它读成一个整数但是它是一个字符串,我不知道如何判断它是不是*。
我的代码如下(显然是不正确的):
string strLine,strChar;
istringstream istr;
int a,b;
while(getline(fin,strChar))
{
istr.str(strLine);
istr>> ws;
istr>>strChar;
if (strChar=="*")
{
break;
}
istr>>a>>b;
}
最佳答案
您可以简单地从 ifstream
对象中提取数字,直到失败为止。
std::ifstream fin("file.txt");
int num1, num2;
while (fin >> num1 >> num2)
{
// do whatever with num1 and num2
}
关于c++ - 如何在C++中读取格式化文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7779798/