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 Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

unix c: switch choices

Status
Not open for further replies.

cruel

Programmer
Aug 6, 2001
131
Hi, I am not a c programmer by training. So, the following must be some thing very basic to a lot fo you. I simply try to allow users to identify a list of variables between item A and item B. From the reference I have, in 'switch' the choice can only be integer. The following piece works OK if users enter 0-9. But, everything is messed if users type anything else. The "invalid reply" warning will be looping on the screen forever. Thanks

...
printf( "Mark the variable ('1 for item A, 0 for item B')? " );
scanf( "%i", &choice );

while ( !( choice == 1 || choice == 2 ) ) {
printf( "Invalid reply. Number '1' or '2' only. Re-enter: ");
scanf( "%i", &choice );
}
switch ( choice ) {
case 1:
...
 
You'd be better off asking in this forum:
(and two things: if the user insists in putting in invalid input, the program *should* keep looping back to ask for valid input. second, you need to do much stronger input validation. that code as it is written is begging for buffer overflow abuse)
 
The loop for invalid input is what I need. Buffer overflow is the question. I switched to getchar and the issue is gone. Thanks!
 
EOF was handled in an outter While Loop, which I did not show here. D&D uses integer for choices a lot, without any obvious validation. Thanks much.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top