0

I have a queation about reading an text file in C++.

Supoose i have a sample.txt file like this:

2
8 5
1 1 1 2 3 4 5 6
4 7
1 2 3 4

the first line of the file means the number of instances(here 2 instances). the second line and third line is the information about the first instence. the third line and fourth line represents the second instances. Below is my main function to read this text file. but when i run it, it just does not work. ie the reading process cannot going on. Anyone can help me out.

int main()
{
    int number;
    string filePath;
    int numberOfInstances;
    int Max;
    int Rings;
    cout << "please input your file path: " ; //ie, D:\\sample.txt

    cin >> filePath;

    ifstream fin;

    fin.open(filePath.c_str());
    if(fin.fail()) {
        cout << "sorry, fail to open" << endl;
        exit(1);
    }

    fin >> numberOfInstances;

    vector<int> vect1;

    for(int i = 0; i < numberOfInstances; i++) {
        fin >> Rings;
        fin >> Max;
        for(i = 0; i < Rings; i++) {
            fin >> number;
            vect1.push_back(number);
        }

        //
        //code to process Vect1, eg, sort it
        //

        for(i = 0; i < Rings; i++) {
            vect1.pop_back();
        }

    }
    fin.close();
    return 0;
}
Barmar
  • 596,455
  • 48
  • 393
  • 495
Hexinwei
  • 15
  • 1
  • 6
  • 2
    You can use the [`getline()`](http://www.cplusplus.com/reference/string/string/getline/?kw=getline) function to read a line from a stream. – user1118321 Aug 23 '14 at 01:36

1 Answers1

2

The problem is that you're using the same variable i for the outer loop over all the instances and the inner loops for the vector elements. So when the inner loop finishes, i is set to 8. Since this is higher than numberOfInstances, the outer loop stops.

Either use a different variable, or use

for (int i = 0; i < Rings; i++)

in the inner loops. The int declaration causes it to create a new variable with just the scope of the loop, so it doesn't overwrite the variable being used in the outer loop.

Make sure you fix both inner loops: the one at the beginning that reads each number and pushes it onto the vector, and the one at the end that pops the off (although you could just use vect1.empty() for that).

Barmar
  • 596,455
  • 48
  • 393
  • 495
  • Jesus, i have made a naive error. it takes me hours to debug it, gosh, i deeply appreciate you pointing it out – Hexinwei Aug 23 '14 at 02:14
  • How many of those hours were spent using an actual debugger, so you could look at the variables as the program went? If you say none, then I think it's time you learned a new skill -- it will pay off dramatially. – Barmar Aug 23 '14 at 02:17