How to get one number from a user

2019-02-24 18:14发布

问题:

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?

回答1:

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.



回答2:

The scanf function is returning a result, the count of successfully read inputs. (And there is also the %n format sequence to get the number of consumed characters.).

So you could use either solutions.

if (scanf(" %d", &menu)  != 1) { 
  /* handle error */
}

or perhaps :

int pos =  -1;
if (scanf(" %d %n", &menu, &pos) <=0 || pos <= 0) {
  /* handle error */
}

My second example is not really useful in your case. But sometimes %n is very useful.

I am putting a space before the %d on purpose: the C library would skip spaces.