zzzzz
zzzzz

Reputation: 1239

Wrong output when parsing the file?

I am using the following code to parse a file.

std::string line;
std::ifstream infile("C:\\t50_20_1.td");

int num;
int pred;
int succ;

while (std::getline(infile, line))
{
    std::istringstream iss(line);
    while(iss >> num || !iss.eof()) {
        if(iss.fail()) {
            iss.clear();
            continue;
        } else {
            std::cout<<num<<std::endl;
        }
    }
    std::cin.ignore();
}

I am trying to print all the numbers in the following file

50
1   35   11   3  13       10  5       11  2       19  1       21  10       23  2       26  3       29  6       35  5       42  10       44  5    
2   3   12   8  7       15  12       19  9       24  6       27  13       29  7       32  8       34  6       35  8       37  9       38  12       39  9    
3   19   7   4  15       8  2       10  7       15  12       21  11       26  9       36  10    
4   35   8   5  13       7  7       10  8       13  13       20  1       21  5       44  1       48  15    

But when the program ends I only get one number as output

50

Upvotes: 1

Views: 64

Answers (1)

localhost
localhost

Reputation: 373

I would recommend you remove the !iss.eof() conditional as it is not necessary in the while loop. The Enter key must be pressed to continue to parse the following lines. Please see the following code. Also, I recommend you add "using namespace std" which implies std:: where necessary and can make the code more readable. Lastly, a few of the variables you are declared are not actually used and so they have been removed from the code below.

#include <fstream>
#include <iostream>
#include <sstream>

using namespace std;

int main (int argc, char ** argv)
{
    string line = "";
    ifstream infile("C:\\t50_20_1.td");
    int num = 0;

    while (getline(infile, line))
    {
        istringstream iss(line);
        while(iss >> num) {
            if(iss.fail()) {
                iss.clear();
                continue;
            } else {
                cout << num << endl;
            }
        }
        std::cin.ignore();
    }
    return 0;
}

Sample Output (selected output only, all numbers are being outputted with the above code)

50
...
44
5
...
39
9
...
48
15

Upvotes: 1

Related Questions