How to get one number from a user

你离开我真会死。 提交于 2019-12-02 00:34:24

问题


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.



来源:https://stackoverflow.com/questions/8808063/how-to-get-one-number-from-a-user

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!