如何阻止用户在C中输入char作为int输入

这是我的代码的一部分:

printf("\nEnter amount of adult tickets:"); scanf("%d", &TktAdult); while (TktAdult<0){ printf("\nPlease enter a positive number!"); printf("\nEnter amount of adult tickets:"); scanf("%d", &TktAdult); } 

现在它只能阻止用户输入负值,但是如何添加它以便它也阻止用户输入char?

以下代码拒绝以下用户输入:

  • 由// 1处理的非数字;
  • 负数由// 2处理;
  • 正数后跟非数字字符,由// 3处理

     while (1) { printf("\nEnter amount of adult tickets: "); if (scanf("%d", &TktAdult) < 0 || // 1 TktAdult < 0 || // 2 ((next = getchar()) != EOF && next != '\n')) { // 3 clearerr(stdin); do next = getchar(); while (next != EOF && next != '\n'); // 4 clearerr(stdin); printf("\nPlease enter a positive number!"); } else { break; } } 

此外,// 4清除缓冲的非数字字符的标准输入,大小为// 3(即123sda - scanf需要123但在缓冲区中留下'sda')。

…阻止用户输入负值…

不可能。 用户输入各种乱码。 相反,读取一行用户输入并解析它的正确性。 使用fgets()进行输入,然后使用sscanf()strtol()等进行解析。

 // return -1 on EOF int GetPositiveNumber(const char *prompt, const char *reprompt) { char buf[100]; fputs(prompt, stdout); fflush(stdout); while (fgets(buf, sizeof buf, stdin)) [ int value; if (sscanf(buf, "%d", &value) == 1 && value > 0) { return value; } fputs(reprompt, stdout); fflush(stdout); } return -1; } // Usage int TktAdult = GetPositiveNumber( "\nEnter amount of adult tickets:" , "\nPlease enter a positive number!"); if (TktAdult < 0) Handle_End_of_File(); else Success(TktAdult); 

但是如何添加它以便它也阻止用户输入char?

您无法阻止用户输入字符值。 您可以做的是检查是否已成功扫描tktAdult 。 如果没有,请从stdin中清除所有内容:

  bool valid = false; while (true) { ... if (scanf("%d", &TktAdult) != 1) { int c; while ((c = getchar()) != EOF && c != '\n'); } else { break; } } 

更好的选择是使用fgets()然后使用sscanf()解析该行。

另见: 为什么每个人都说不使用scanf? 我该怎么用? 。

 // You can try this, Filter all except for the digital characters int TktAdult; char ch; char str[10]; int i = 0; printf("\nEnter amount of adult tickets:"); while ((ch = getchar()) != '\n') { // Filter all except for the digital characters if(!isalpha(ch) && isalnum(ch)) str[i++] = ch; } str[i] = '\0'; TktAdult = atoi(str); printf("Done [%d]\n", TktAdult);