I’m just learning C, and having worked with languages as javascript and php up till now, i am having trouble converting some of my thinking steps to the possibilities of C. The program i am writing ( that sounds bigger than it really is ) uses an input menu that lets the user pick an option. The options can be 1, 2 or 3.
Now, i’m doing:
int menu;
scanf("%d", &menu);
Which works fine. However, entering a character of a string will cause problems.
In javascript i’d simply match the menu variable against the options:
if ( menu != 1 && menu != 2 && menu != 3 ){
menu = 4; // a switch later on will catch this.
}
However, that does not seem to work in C.
How should i approach this?
You should check for errors:
(On success,
scanfreturns the number of items that you wanted to read.) How you handle the error is up to you. You could loop until you have a valid value, or abort immediately, or set the variable to a default value.An alternative is to read a whole line of input with
fgetsand then attempt to tokenize and interpret that, e.g. withstrtokandstrtol.