c++ - 如何在C++中读取格式化文件

标签 c++

我有以下格式。每行有两个整数,文件以“*”结尾。我怎样才能从文件中读取这两个数字。谢谢。

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/

相关文章:

c++ - 巨大的 initializer_list 编译段错误

c++ - 使用 BOOST_FOREACH 时如何测试 vector 中的最后一个元素?

c++ - 你如何通过 STL 列表向后迭代?

c++ - 在 Visual C++ 6 中显示文件夹选择对话框

c++ - boost .Asio : Reading input from SSL-Socket results in incomplete data

c++ - 在 void 指针上使用 delete[] 运算符释放内存

c++ - 模板编译

c++ - 改变静态链接 DLL 的 DLL 搜索路径

c++ - 具有依赖参数类型的概念约束成员函数

c++ - 警告 : non-static data member initializers - c++