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

时间:2011-10-15 18:30:34

标签: 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;
}

3 个答案:

答案 0 :(得分:4)

您可以简单地从ifstream对象中提取数字,直到它失败。

std::ifstream fin("file.txt");

int num1, num2;
while (fin >> num1 >> num2)
{
    // do whatever with num1 and num2
}

答案 1 :(得分:1)

我很想使用好的fscanf() method,请在MSDN上查看一个简单明了的例子。

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

答案 2 :(得分:1)

解决方案是使用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));
    }
}
相关问题