Getline truncating first character in loop

Hi, all. My problem lies in a do-while loop that works correctly on the first go, but subsequent inputs truncate the first character of the input. Any ideas as to why this is happening? I'm guessing it's a newline character stuck in the buffer, but cin.clear, cin.ignore(1000, '\n'), and cin.get() have not cleared it out, no matter where I put them in the loop. Here's my code:

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
42
43
44
45
46
47
48
49
50
51
int validateInt(bool allowNegatives)
{      
   int validated;
   string input = "";
   stringstream ssTemp;
   bool valid;
   
   cin.ignore();
   cin.clear();
   
   getline(cin, input);
   
   do
   {
      valid = true;  
      
      /*This forces user to re-enter input if any char in the input string 
      is not a digit */
      for(int i = 0; i < input.length(); i++)  
      {           
         if(!isdigit(input[i]))
         {
            //This allows a negative sign in first input position       
            if(input[i] == '-' && i == 0 && allowNegatives)                   
               continue;
            
            if(allowNegatives)                   
               cout<<"Invalid input! Please enter an integer: ";
            else
               cout<<"Invalid input! Please enter a positive integer: ";
            
            valid = false;    
            cin.clear();            //clear error flags
            cin.ignore(1000,'\n'); //clear input buffer    
            input="";               //clear previous data from input 
            getline(cin, input);
            break;  
         } 
      }   
   
   }while(!valid);
   
   //DEBUGGING ONLY
   cout<<"input is: "<<input<<"\n";
   
   //Temporary stringstream is used to easily convert from string to int
   ssTemp<<input;
   ssTemp>>validated;

   return validated;
}
Get rid of line8.
I'm kinda a newbie at c++, so I could be wrong, but the way it looks like you have it set up is good and all, but it will go to the next integer anyway instead of checking the integer you messed up on O_o I'm not sure what truncate means though, so I cant help you there xD
Thanks for the solution, aruawons! I fixed the syntax of that ignore statement and moved it to an earlier spot in the program, outside of the function call.
Last edited on
Topic archived. No new replies allowed.