Harry
Harry

Reputation: 95

Skip non-integers from text file C++

I have a program which reads integers from a text file and skips non-integers and strange symbols. Then text file looks like:

# Matrix A   // this line should be skipped because it contains # symbol
1 1 2
1 1$ 2.1      // this line should be skipped because it contains 2.1 and $
3 4 5

I have to print out the matrix without strange symbols and non-integers line. That is the output should be:

1 1 2
3 4 5

My code

ifstream matrixAFile("a.txt", ios::in); // open file a.txt
if (!matrixAFile)
{
      cerr << "Error: File could not be opened !!!" << endl;
      exit(1);
}

int i, j, k;
while (matrixAFile >> i >> j >> k)
{
      cout << i << ' ' << j << ' ' << k;
      cout << endl;
}

But it fails when it gets the first # symbol. Anyone helps please ?

Upvotes: 1

Views: 2671

Answers (5)

Kerrek SB
Kerrek SB

Reputation: 476950

If you are set to three integers per row, I suggest this pattern:

#include <fstream>
#include <sstream>
#include <string>

std::ifstream infile("matrix.txt");

for (std::string line; std::getline(infile, line); )
{
    int a, b, c;

    if (!(std::istringstream(line) >> a >> b >> c))
    {
        std::cerr << "Skipping unparsable line '" << line << "'\n";
        continue;
    }

    std::cout << a << ' ' << b << ' ' << c << std::endl;
}

If the number of numbers per line is variable, you could use a skip condition like this:

line.find_first_not_of(" 0123456789") != std::string::npos

Upvotes: 1

Jerry Coffin
Jerry Coffin

Reputation: 490048

I think I'd just read a line at a time as a string. I'd copy the string to the output as long as it contains only digits, white-space and (possibly) -.

Upvotes: 0

Since it's an assignment, I'm not giving full answer.

Read the data line by line to a string(call it str),
Split str into substrings,
In each substring, check if it's convertible to integer value.

Another trick is to read a line, then check that every char is between 0-9. It works if you don't need to consider negative numbers.

Upvotes: 0

Dietmar K&#252;hl
Dietmar K&#252;hl

Reputation: 153792

Of course, this fails at the # character: The # isn't an integer and, thus, reading it as an integer fails. What you could do is try to read three integers. If this fails and you haven't reached EOF (i.e., matrixAFile.eof() yields false, you can clear() the error flags, and ignore() everything up to a newline. The error recovery would look something like this:

matrixAFile.clear();
matrixAFile.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

Note, that you need to bail out if you failed because eof() is true.

Upvotes: 0

Drew Dormann
Drew Dormann

Reputation: 63704

Your problem is with this code.

int i, j, k;
while (matrixAFile >> i >> j >> k)

The assignment is "Find out if the line contains integers"

But your code is saying "I already know that the line contains integers"

Upvotes: 1

Related Questions