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:
int menu;
if (scanf("%d", &menu) != 1)
{
/* error */
/* e.g.: */ menu = 4;
}
(On success, scanf returns 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 fgets and then attempt to tokenize and interpret that, e.g. with strtok and strtol.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With