为什么将整数从文件读取到2D向量导致所有值均为零

Why reading integers from file into a 2d vector is resulting all values to be zero?

本文关键字:向量 整数 文件 读取 2D 为什么      更新时间:2023-10-16

我正在尝试将文本文件的整数矩阵读取到2D矢量中。

输入数据:

4 5

0 -0.5 -3 -1 -4

40 1 1 1 1

10 -2 -1 1 1

10 0 1 0 -1

我的代码:

    ifstream InFile("Simplex_EX1.txt");
    if (!InFile.is_open())
        cout << "File could not be opened correctly";
    vector<vector<int>> MyData;
    int Rows, Columns;
    InFile >> Rows >> Columns; // read first line - working
    MyData.resize(Rows);
    for (int i = 0; i < Rows; i++)
        MyData[i].resize(Columns);
    for (int i = 0; i < Rows; i++)
        for (int j = 0; j < Columns; j++)
            InFile >> MyData[i][j]; // read the rest - not working
    InFile.close();

因此,我成功阅读了第一行,因此我正确调整了向量大小。但是,最终向量只是零。有人可以告诉我我在做什么错吗?请感谢

您正在尝试将浮点数 -0.5读取为失败的整数。一旦流失败,在清除错误之前,它将不会读取其他内容。