Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

"cin" errorr

Status
Not open for further replies.

jtgurkin

Technical User
Sep 16, 2002
47
US
I am writing a program and am using the cin command.
I have one problem, if I specify for the program to take an integer variable and someone accidently enters a character or if I am using an array and someone enters in too many characters for the array the next time a cin statement comes up, the program skips over it and goes to the next step. This puts my program in an infinite loop and it is no longer useful. How can I remove this problem to keep from my program screwing up by simple human input error.
 
You might want to read it in the input intially character by character, appending it to a string (or char array). For each character, you can use the "isdigit" function to determine if the character is a digit or not. (If you support +/- for signs, you might want to handle that seperately too.) When you have received all the input from the person, simply use atoi to convert it to an integer.

Hopefully that helps,

Kelek
 
Here is the code:

void main()
{

int program;

system("cls");

heading();

cout << endl << endl;
cout << &quot; MAIN MENU&quot; << endl << endl;
cout << &quot; 1. Weekly Wage Calculator | 2. Format Disk&quot; << endl;
cout << &quot; 3. Install Program | 4. MS-Dos Prompt&quot; << endl;
cout << &quot; 5. Print Test |&quot; << endl;
cout << &quot; 9. LOGOFF&quot;;
cout << endl;
cout << &quot;ENTER SELECTION: &quot;;
cin >> program;

if(program >=1 && program <=5 || program == 9)
switch(program)
{
case 1:
wages();
main();
break;
case 2:
system(&quot;cls&quot;);
system(&quot;format a:&quot;);
main();
break;
case 3:
system(&quot;cls&quot;);
system(&quot;a:&quot;);
system(&quot;install&quot;);
system(&quot;setup&quot;);
main();
break;
case 4:
system(&quot;cls&quot;);
cout << &quot;Please wait...&quot; << endl;
system(&quot;command.com&quot;);
main();
break;
case 5:
system(&quot;cls&quot;);
main();
break;
case 9:
return;
break;
}
else
program = 0;
main();


return;
}
It's not an array for this part, this is where the code messes up most often due to human error: at the line
&quot;cin >> program;&quot; if you put in a character there it causes the program to go into an infinite loop.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top