How to stop user entering char as int input in C

时光毁灭记忆、已成空白 提交于 2019-11-28 06:33:11

问题


Heres a part of my code:

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

Right now it can only stop user from entering a negative value, but how do I add to it so it also stops user from entering a char??


回答1:


The following code rejects user input that are:

  • non-numeric as handled by // 1;
  • negative numbers as handled by // 2;
  • positive numbers followed by non-numeric chars as handled by //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;
        }
    }
    

Also, // 4 clears the standard input of buffered non-numeric characters following case // 3 (i.e. 123sda - scanf takes 123 but leaves 'sda' in the buffer).




回答2:


... stop user from entering a negative value ...

is not possible. Users enter all sorts of gibberish. Instead, read a line of user input and parse it for correctness. Use fgets() for input, then sscanf(), strtol(), etc. for parsing.

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



回答3:


but how do I add to it so it also stops user from entering a char??

You can't prevent user from entering character values. What you can do is check if tktAdult was successfully scanned. If not, flush out everything from stdin:

 bool valid = false;
 while (true) {
 ...

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

The better alternative is to use fgets() and then parse the line using sscanf().

Also see: Why does everyone say not to use scanf? What should I use instead?.




回答4:


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


来源:https://stackoverflow.com/questions/41145908/how-to-stop-user-entering-char-as-int-input-in-c

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