开发者

How to prevent menus from glitching when scanf expects an int but receives characters (C)

Take for instance:

printf("Continue?\n>>");
scanf("%d", &cont);
getchar();

Normally I add the getchar() to prevent the program from infinite looping (reading off the '\n' character from the buffer). However, when used with a menu following this statement the extra characters are read in and any scanfs following the character input (up to the number of characters input) are skipped.

What I want to figure out is how to prevent it from skipping forward through several sections开发者_开发百科 of my program when it reads in a type of input other than an int. Would this be best solved by putting it inside of a loop that won't continue until the variable is in the expected domain?


Consider using fgets and sscanf instead. Load a line's worth of input, then parse only that line instead of the entire stdin.


Check the value returned by scanf. The return value indicates the number variables that were assigned to. If you're expecting an int and the user types in a character, scanf should return zero.

Try including a "%*s" input specifier. See http://www.cplusplus.com/reference/clibrary/cstdio/scanf/


Instead of reading an integer, just read a string and convert it to a number (atoi). Two problems that may occur:

  1. Char buffer not big enough. To prevent this you can read char by char from the input and realloc the buffer if necessary.
  2. String is not a number. Atoi will return some default value (0 or -1, don't remember). You just have to check the string somehow.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜