2

出于某种原因,如果用户输入了错误的数据类型,例如 'j' 或 '%',循环将停止要求输入,并且会"Enter an integer >"一遍又一遍地显示。如何让程序处理错误的输入?为什么输入非数值会导致这种奇怪的行为?

#define SENTINEL 0;
int main(void) {
  int sum = 0; /* The sum of numbers already read */
  int current; /* The number just read */

  do {
    printf("\nEnter an integer > ");
    scanf("%d", &current);
    if (current > SENTINEL)
      sum = sum + current;
  } while (current > SENTINEL);
  printf("\nThe sum is %d\n", sum);
}
4

2 回答 2

3

如果scanf()找不到匹配的输入,current变量将保持不变:检查返回值scanf()

/* scanf() returns the number of assignments made.
   In this case, that should be 1. */
if (1 != scanf("%d", &current)) break;

如果您希望在无效输入后继续接受输入,则需要读取无效数据,因为它将保留,正如评论中的pmgstdin所指出的那样。一种可能的方法是使用读取输入但不执行赋值的格式说明符:"%*s"

if (1 != scanf("%d", &current))
{
    scanf("%*s");
}
else
{
}
于 2012-07-03T15:30:48.177 回答
1

One way would be to read the input into a string and then convert the string to the data type you want.

My C is a bit rusty, but I recall using fgets() to read the string, and then sscanf() to parse/"read" the string into the variables I was interested in.

于 2012-07-03T15:30:55.803 回答