How to get one number from a user

我怕爱的太早我们不能终老 提交于 2019-12-01 21:55:40

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.

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.

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