返回到文件开头后,ifstream in循环卡在相同的值上

问题描述 投票:-1回答:1

我正在尝试编写一个从文件中读取值并将它们放在矩阵中的函数。矩阵(两列)是通过扫描文件中的行数并使用该数字作为矩阵中的行数来制作的。要读取值,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 
c++
1个回答
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
© www.soinside.com 2019 - 2024. All rights reserved.