Skip non-integers from text file !!!

I have a programming assignment which reads integers from a text file and skips non-integers (in first two columns) and strange symbols. Then text file looks like:

# Matrix A // this line should be skipped because it contains # symbol
1 1 2
3 k 4 // this line should be skipped because it contains "k"
1 1 2.1
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 a 4
3 4 5


My code
1
2
3
4
5
6
7
8
9
10
11
12
13
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 ?
Last edited on
Since it fails when it finds an invalid symbol on a line u should validate the line before extracting the integers. getline could be useful for this...
U could also use stringstream with the ws manipulator and attempt to store the whole line into an integer - if it fails then discard the line...
Last edited on
I already tried your way. I used istringstream to convert substrings into integers but when I converted "4$", it is still converted into "4", while it is supposed to skip it. And I don't know how to discard a line. I tried to google it for 2hrs, but still don't have answer.
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
int i, j, k;
string line;
istringstream iss;   //#include <sstream>

while (getline(matrixAFile, line)) 
{
   if (goodLine(line))
   {
       iss.clear();    //clear iss first
       iss.str(line);  //load line into iss

       iss >> i >> j >> k;  //use iss as cin
       cout << i << ' ' << j << ' ' << k;
       cout << endl;
   }
}


goodLine(string) determines if line contains only digits and spaces.

1
2
3
4
5
6
7
8
9
10
11
bool goodLine(string line)
{
   for (int i = 0; i < line.length(); i++)
   {
      if (!isdigit(line[i]) && !isspace(line[i]))  //#include <cctype> 
      {
         return false;
      }
   }
   return true;
}
Tks tntxtnt a lot. That works. But I just edited my questions a little bit. Actually the third column in the text file is a real number and I need to keep that real numbers as I mention in my edited post. Your program skips real numbers as well. Are there any way we could keep that? Tks.
So now u have to keep good rows AND good columns ?
U'll be better off using a 2d array and attempt to store every potential integer that u find (i'm assuming u mean integer when u say 'real number') using a method like tntxtnt's. Whenever an attempt fails flag that spot in the array as an error. Then u can easily determine if a row or a column is good by iterating through the array and build ur matrix.
Last edited on
Topic archived. No new replies allowed.