在 C++ 中使用 getline 和 >> 运算符检查输入文件

Input file checking using getline an >> operator in c++

我在这里编写了一个代码,它逐行读取输入文件并创建一个向量向量,然后我将其用作稍后在我的家庭作业中使用的矩阵。这是代码:

vector<vector<int>> inputMatrix;
string line;
while(!file.eof())
{
    getline(file, line);
    stringstream ss(line);

    int num;
    vector<int> temp;

    while(ss >> num)
    {
        temp.push_back(num);        
    }
    inputMatrix.push_back(temp);
}

但是,某些输入文件可能包含非整数值。我想为矩阵创建集成一个输入检查功能,这样当输入文件中有一个非整数值时,我的程序就会退出。

我怎样才能做到这一点?可以在这个 while 循环中的某处或代码中的其他地方写吗?

非常感谢您。

来自cppreference.com

If extraction fails, zero is written to value and failbit is set. If extraction results in the value too large or too small to fit in value, std::numeric_limits::max() or std::numeric_limits::min() is written and failbit flag is set.

因此您可以在 while 循环之后简单地添加一个 if 子句:

while (ss >> num)
{
  temp.push_back(num);
}
if (ss.fail()) // explicitly check for failbit
{
  expected_integer_error();
}

I would like to integrate a input check feature for the matrix creation so that when there is a non-integer value in the input file, my program would quit.

stringstream 已经为您进行了此项检查。您可以在 while 循环之后简单地测试它的状态。如果未能解析非整数值,则 failbit 将设置为 true。

这里是 working demo(有一些小的改进):

#include <iostream>
#include <vector>
#include <sstream>
using namespace std;

int main() {
    vector<vector<int>> inputMatrix;
    string line;
    while(getline(cin, line))
    {
        istringstream iss(line);

        int num;
        vector<int> temp;

        while(iss >> num)
        {
            temp.push_back(num);        
        }
        if(!iss) {
            cout << "Bad input detected!" << endl;
            return 1;
        }
        inputMatrix.push_back(temp);
    }
    return 0;
}

输入

12 13 46 3
42 2.6 5

输出

Bad input detected!