0

I have got an input file with following data

2
100
2
10 90
150
3
70 10 80

Now, I am able to read till 4th line ( 10 90) but when reading 5th line(150), the file pointer seems to be stuck at 4th line. I have tried infile.clear() just incase. How do I make sure that file pointer is moving correctly or position it at next line? Appreciate your feedback.

-Amit

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

using namespace std;

int main(void) {

int cases;
int total_credit=0;
int list_size=0;
string list_price;


//Read file "filename".

ifstream infile;
infile.open("A-large-practice.in",ifstream::in);
if(!infile.is_open()) {
    cout << "\n The file cannot be opened" << endl;
    return 1;
}

else {
    cout<<"Reading from the file"<<endl;
    infile >> cases;       
    cout << "Total Cases = " << cases << endl;
    int j=0;

    while (infile.good() && j < cases) {

        total_credit=0;
        list_size=0;

        infile >> total_credit;
        infile >> list_size;

        cout << "Total Credit = " << total_credit << endl;
        cout << "List Size = " << list_size << endl;
        //cout << "Sum of total_credit and list_size" << sum_test << endl; 

        int array[list_size];
        int i =0;
        while(i < list_size) {
            istringstream stream1;  
            string s;
            getline(infile,s,' ');
            stream1.str(s);
            stream1 >> array[i];
            //cout << "Here's what in file = " << s <<endl;
            //array[i]=s;
            i++;
        }

        cout << "List Price = " << array[0] << " Next = " << array[1] << endl;          
        int sum = array[0] + array[1];
        cout << "Sum Total = " << sum << endl;
        cout <<"Testing" << endl;   
        j++;    
    }       
}   
return 0;   

}
Amit
  • 1
  • 1
  • 3

1 Answers1

1

The problem is that you're using ' ' (space) as your "line terminator" for getline. So when you're reading the numbers on line 4 into the string s, the first one will be "10" and the second will be "90\n150\n3\n70" -- that is, everything up to the next space. This is almost certinaly not what you want and is leading to your confusion about where you are in the file. The next number you read will be 10, leading you to think you're on line 4 when in fact you're on line 7.

edit

The easiest way to fix this is probably to not use getline at all and just read ints directly from the input:

while (i < list_size)
    infile >> array[i++];

This ignores the newlines altogether, so the input might as well be all on one line or split between lines randomly, but as you have an initial number that tells you how many numbers to read, that's just fine.

Chris Dodd
  • 119,907
  • 13
  • 134
  • 226
  • You are right Chris. I see what you mean. I was wondering if there's a way out where I can avoid it else I am thinking of using vectors to parse the string line containing number list. – Amit Feb 15 '13 at 03:38