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

how to read the formatted file in C++

本文关键字:读取 格式化 文件 c++      更新时间:2023-10-16

我有以下格式。每行有两个整数,文件以"*"结尾。我如何从文件中读取这两个数字?谢谢。

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
}

我更喜欢使用老式的fscanf()方法,请参阅MSDN上一个简单而直接的示例。

  1. 作为第一步,将整行读入字符串缓冲区
  2. 检查是否等于"*"
  3. 如果不是,使用sscanf()解析两个整数

解决方法是使用std::istream逐行读取文件。然后,处理每个输入行并将数字存储到一个列表中。

// open the file.
std::string path = "path/to/you/file";
std::ifstream file(path.c_str());
if (!file.is_open()) {
    // somehow process error.
}
// read file line by line.
std::vector< std::pair<int,int> > numbers;
for (std::string line; std::getline(file,line);)
{
    // prepare to parse line contents.
    std::istringstream parser(line);
    // stop parsing when first non-space character is '*'.
    if ((parser >> std::ws) && (parser.peek() == '*')) {
       break;
    }
    // store numbers in list of pairs.
    int i = 0;
    int j = 0;
    if ((parser >> i) && (parser >> j)) {
        numbers.push_back(std::make_pair(i, j));
    }
}