cin.ignore() confusion...

Ok, this has been throwing me off in my programs for a while now. I don't understand why sometimes it works just fine and sometimes it creates a need for a keyboard entry to continue. Here is some example code where I am having the issue with cin.ignore() needing a return after the getline() function.

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
     bool validfile = false;
     while (!validfile)
     {
         if (retrycnt == 0)
         {
             cout << "Sorry, your file is in another castle...\n\n";
             exit(0);
         }
         cout << "Hello! What file are we checking? ";
         getline(cin, filename);
 
         cin.ignore(1, '\0');
         infile.open (filename.c_str());
 
         if (!infile && retrycnt > 1)
         {
             cout << "File not found! " << retrycnt - 1 << " attempts remaining...   \n\n";
             retrycnt--;
         }
         else if (!infile && retrycnt == 1)
             retrycnt--;
         else
         {
             validfile = true;
             continue;
         }
     }


I have written this loop a thousand times! Ok, maybe not a thousand... but sometimes it works like a charm and other times like this, it's acting like there are still some characters or a character stuck in the buffer. This is so confusing! Help?

-Arcie
try making cin.ignore(1, '\n'); to cin.ignore(1000, '\n');
Topic archived. No new replies allowed.