返回文件开头后,ifstream循环停留在相同的值上

时间:2019-03-23 17:53:37

标签: c++

我正在尝试编写一个从文件中读取值并将其放入矩阵的函数。通过扫描文件中的行数并将该数字用作矩阵中的行数,可以创建(两列的)矩阵。要读取值,请将ifstream对象reader带回到文件的开头。但是,这样做之后,reader被卡在整个循环的整数(我认为这是垃圾值)上。动态分配矩阵的功能可以正常工作。

我在下面包括了MCVE。

#include <fstream>
#include <iostream>
#include <string>

using namespace std;

int main(){

    string fileChoice;
    cout << "Choose a file to open: ";
    cin >> fileChoice;

    ifstream reader;
    reader.open(fileChoice);
    if (reader.fail()){
        cerr << fileChoice << " could not be opened" << endl;
        system("pause");
        exit(1);
    }

    // https://stackoverflow.com/questions/26903919/c-allocate-dynamic-array-inside-a-function
    int** Matrix = new int*[4];  
    for (int i = 0; i < 4; i++)  {
        Matrix[i] = new int[2];
    }

    reader.seekg(0, ios::beg);
    for (int i = 0; i < 4; i++){
        for (int j = 0; j < 2; j++){
            reader >> Matrix[i][j];
            cout << Matrix[i][j] << " ";
        }
    }

    system("pause");
    exit(0);
}

这是我使用的示例文件中的数据:

1 10
2 10
11 20
23 30

这是我期望的cout输出:

1 10 2 10 11 20 23 30

但这是我得到的:

-842150451 -842150451 -842150451 -842150451 -842150451 -842150451 -842150451 -842150451 

此外,更改时

    reader.seekg(0, ios::beg);
    for (int i = 0; i < 4; i++){
        for (int j = 0; j < 2; j++){
            reader >> Matrix[i][j];
            cout << Matrix[i][j] << " ";
        }
    }

    int beg;
    reader.seekg(0, ios::beg);
    for (int i = 0; i < 4; i++){
        for (int j = 0; j < 2; j++){
            reader >> beg;
            cout << beg << " ";
        }
    }

我得到以下输出:

-858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 

1 个答案:

答案 0 :(得分:0)

当我拿到代码时,您现在在问题中,然后添加reader.clear();来获得此信息:

#include <fstream>
#include <iostream>
#include <string>

using namespace std;

int main(){

    string fileChoice;
    cout << "Choose a file to open: ";
    cin >> fileChoice;

    ifstream reader;
    reader.open(fileChoice);
    if (reader.fail()){
        cerr << fileChoice << " could not be opened" << endl;
        system("pause");
        exit(1);
    }

    // https://stackoverflow.com/questions/26903919/c-allocate-dynamic-array-inside-a-function
    int** Matrix = new int*[4];  
    for (int i = 0; i < 4; i++)  {
        Matrix[i] = new int[2];
    }

    reader.clear();
    reader.seekg(0, ios::beg);
    for (int i = 0; i < 4; i++){
        for (int j = 0; j < 2; j++){
            reader >> Matrix[i][j];
            cout << Matrix[i][j] << " ";
        }
    }
}

...并在包含您在问题中给出的数据的文件上运行它,我得到的输出如下:

1 10 2 10 11 20 23 30