簡體   English   中英

如何阻止用戶在 C 中輸入字符作為 int 輸入

[英]How to stop user entering char as int input in C

這是我的代碼的一部分:

    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);
    }

現在它只能阻止用戶輸入負值,但是我如何添加它以便它也阻止用戶輸入字符?

... 阻止用戶輸入負值 ...

不可能。 用戶輸入各種亂碼。 相反,讀取一行用戶輸入並解析它的正確性。 使用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);

但是我如何添加它以便它也阻止用戶輸入字符?

您無法阻止用戶輸入字符值。 您可以做的是檢查tktAdult已成功掃描。 如果沒有,請從標准輸入中清除所有內容:

 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);

以下代碼拒絕用戶輸入:

  • 由 // 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' 留在緩沖區中)。

#include <stdio.h>

int main() {
    int x = 0.0;
    int readReasult;
    while(1)
    {
        readReasult = scanf("%d",&x);
        if (readReasult < 0) break;
        if (readReasult == 1) {
            if (x >= 0)
                printf("next number: %d\n", x);
            else
                printf("negative value not expected\n");
        } else {
            clearerr(stdin);
            scanf("%*s");
            printf("wrong input\n");
        }
    }

    return 0;
}

https://godbolt.org/z/xn86qz

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM