【问题标题】:Input file checking using getline an >> operator in c++在 C++ 中使用 getline 和 >> 运算符检查输入文件
【发布时间】:2017-07-08 19:12:45
【问题描述】:

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

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循环中的某个地方或代码中的其他地方编写?

非常感谢您。

【问题讨论】:

标签: c++ algorithm input getline


【解决方案1】:

来自cppreference.com

如果提取失败,则将零写入 value 并设置 failbit。如果 提取导致值太大或太小而无法适应 值,std::numeric_limits::max() 或 std::numeric_limits::min() 已写入并设置了故障位标志。

所以你可以简单地在你的 while 循环之后添加一个 if 子句:

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

【讨论】:

  • if(!ss) { ...应该足够了。
【解决方案2】:

我想为矩阵创建集成输入检查功能,以便当输入文件中有非整数值时,我的程序会退出。

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!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-24
    • 1970-01-01
    • 2014-01-11
    • 2022-11-04
    • 2017-09-12
    • 2017-03-31
    • 2015-06-11
    相关资源
    最近更新 更多