Infine Loop problem

Hello,
I have my program running into an infinite loop and I can't seem to find out where the issue is.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
int main()
{
    const int arraySize = 5;
    int indexOfArray = 0;
    Book bookList[arraySize];
    double tempPrice;//temporary stores price
    string tempStr;//temporary stores author, title
    string test;


    fstream fileIn( "file.txt" );

            while ( !fileIn.eof( ))
        {
            getline(fileIn,tempStr);
           test =  bookList[indexOfArray].getName(tempStr);


           // getline(fileIn,tempStr);
           // bookList[indexOfArray].setTitle(tempStr);

           // fileIn >> tempPrice;
           // bookList[indexOfArray].setPrice(tempPrice);
                cout << indexOfArray;
                cout << arraySize;
            if ( indexOfArray < arraySize )//shifting array index while not exceeding array size
            {
                indexOfArray++;
                cout << test;
            }
        }
        //system("PAUSE");

    fileIn.close();
    for (int i = 0; i < arraySize; i++)
    {
        cout << test << endl;
    }
return 0;
}


When I go to test the code all I get 5's across the screen and displaying in my infinite loop.
I'd guess that your "file.txt" file isn't being opened correctly.

You need to check fileIn.is_open() before doing anything else as fileIn.eof() won't tell you if the open failed - you'll just end up going round and round the while loop.

Cheers,
Jim
A better way is to put getline inside the while condition. That way you will only read as long as getline succeed.

while (getline(fileIn,tempStr))
Indeed!
umm first of all don't use system pause because it is evil. second could it be that the while loop works until end of file is reached and I don't see where eof is made true thus the infinite loop. I dont really understand eof though so i could be wrong
As jim80y said you need to check for the fileIn.is_open() condition
as
1
2
3
4
5
if(  ! fileIn.is_open() ) 
{
              cout<<"\n File opening error";
		return 0;
}
Topic archived. No new replies allowed.