[try Beta version]
Not logged in

 
while loop, loops forever

Oct 5, 2010 at 8:35pm
Why does this keep looping forever?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
    std::string word;

    while(file.is_open()){
         file >> word;
         
         Element item;

         sort.retrieve(word, item);
         
         if(item.count == 0){
             item.count++;
             sort.insert(item);
         }
         else{
             item.count++;
             sort.replace(item);
         } 
    }
    file.close();
    
    return;


I want this to loop until the file is empty.
Last edited on Oct 5, 2010 at 8:49pm
Oct 5, 2010 at 8:51pm
Because you're not closing the file anywhere inside the loop...
Perhaps while(file >> word) would be more appropriate.
Oct 5, 2010 at 8:55pm
I assume you want to read the whole file. So instead of

1
2
3
4
5
6
7
std::string word;
while(file.is_open())
{
    file >> word;
    // code
}
file.close();

you should say

1
2
3
4
5
6
std::string word;
while(file >> word)
{
    // code
}
// no need to call close(), let the scope deal with it 

It's also worth noticing that since item.count will be incremented no matter what, it can be said only once, outside the if statement.
Last edited on Oct 5, 2010 at 8:56pm
Topic archived. No new replies allowed.