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:
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;
}
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.