1

I have written a code here which reads a input file line by line and creates a vector of vectors which I then use as a matrix, later on, in my homework. This is the code:

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);
}

However, some input files may contain non-integer values. 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.

How can I achieve this? Would it be possiple to write somewhere in this while loop or somewhere else in the code?

thank you very much in advance.

byetisener
  • 178
  • 11
  • 4
    [Why is iostream::eof inside a loop condition considered wrong?](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) – Biffen Feb 19 '17 at 15:05

2 Answers2

1

From 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.

So you could simply add an if clause after your while loop:

while (ss >> num)
{
  temp.push_back(num);
}
if (ss.fail()) // explicitly check for failbit
{
  expected_integer_error();
}
Maikel
  • 1,094
  • 6
  • 17
0

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.

The stringstream already does this check for you. You can simply test its state after the while loop. If it failed to parse a non integer value, the failbit will be set to true.

Here's a working demo (with some small improvements):

#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;
}

Input

12 13 46 3
42 2.6 5

Output

Bad input detected!
πάντα ῥεῖ
  • 83,259
  • 13
  • 96
  • 175