C语言程序设计整数验证

dzjeubhm  于 2022-12-03  发布在  其他
关注(0)|答案(5)|浏览(169)
int main() {
    int choice;
    printf("\n----------Welcome to Coffee Shop----------");
    printf("\n\n\t1. Login   ");
    printf("\n\t2. Sign Up ");
    printf("\n\nPlease enter 1 or 2: ");
    scanf(" %d", &choice);
    system("cls||clear");
    
    //put while loop to check
    switch (choice) {
    case 1:
        system("cls||clear");
        login();
        break;
    case 2:
        system("cls||clear");
        user_signup();
        break;
    default:
        printf("\nInvalid Number\n");
        main();
        break;
    }

    return 0;
}

如果输入不是int,我如何让用户重新输入?我尝试使用isdigit(),但它不起作用,我可以知道解决方案是什么吗?

ef1yzkbh

ef1yzkbh1#

scanf返回匹配成功的输入项的数量。因此,您可以构建一个循环,该循环一直运行到恰好得到一项为止。
一个非常简单的方法是:

while(1)
{
    int res = scanf(" %d", &choice);

    if (res == 1) break;  // Done... the input was an int

    if (res == EOF) exit(1); // Error so exit

    getchar();  // Remove an discard the first character in stdin
                // as it is not part of an int
}

printf("Now choice is an int with value %d\n", choice);

也就是说,我建议您看看fgetssscanf

o7jaxewo

o7jaxewo2#

scanf(" %d", &choice);无法处理转换后的输入超出int范围的情况。这会导致 * 未定义的行为 *。
使用scanf()删除。
使用fgets()将用户输入的 line 读入 string,然后进行验证。
如需str2subrange()的详细信息,请参阅Why is there no strtoi in stdlib.h ?

bool validate_int(const char *s, int *value) {
  const int base = 10;
  char *endptr;
  errno = 0;
  long lvalue = str2subrange(s, &endptr, base, INT_MIN, INT_MAX);
  // For OP's case, could instead use 
  long lvalue = str2subrange(s, &endptr, base, 1, 2);
  if (value) {
    *value = (int) lvalue;
  }
  if (s == endptr) {
    return false; // No conversion
  }
  if (errno == ERANGE) {
    return false; // Out of range
  }

  // Skip trailing white-space
  while (isspace(((unsigned char* )endptr)[0])) {
    endptr++;
  }

  if (*endptr != '\0') {
    return false; // Trailing junk
  }

  return true;
}
zlhcx6iw

zlhcx6iw3#

我认为最好是以字符串的形式接收,然后检查是否所有字符都是数字,如果所有字符都是数字,则将其转换为int
就像这样

int main() {
    int choice;
    char chars[100];
    printf("\n----------Welcome to Coffee Shop----------");
    printf("\n\n\t1. Login   ");
    printf("\n\t2. Sign Up ");
    printf("\n\nPlease enter 1 or 2: ");
    scanf(" %s", chars);
    choice = stringToInteger(chars);
    system("cls||clear");

    //put while loop to check
    switch (choice) {
    case 1:
        system("cls||clear");
        login();
        break;
    case 2:
        system("cls||clear");
        user_signup();
        break;
    default:
        printf("\nInvalid Number\n");
        main();
        break;
    }

    return 0;
}

int stringToInteger(char* chars)
{
    int i = 0, number = 0;

    while(chars[i] >= '0' && chars[i] <= '9')
    {
        number = chars[i++] - '0' + number * 10;
    }

    return number;
}
qyswt5oh

qyswt5oh4#

scanf()函数返回已成功转换和赋值的字段数。因此,在scanf(" %d", &choice);行中,可以执行以下操作:

do {
    printf("\n\nPlease enter 1 or 2: ");
    int result=scanf(" %d", &choice);
    if (result==1) {
        break;
    }
    printf("\nInvalid Number\n");
} while (1);
6rqinv9w

6rqinv9w5#

您应该使用循环来代替递归调用main()。还可以考虑使用getchar()而不是scanf来输入单个字符。例如,下面的代码可以完成您想要的操作。

#include <stdio.h>
#include <stdlib.h>

int main() {
    int valid_choice = 0;
    while (!valid_choice) {
        printf("\n----------Welcome to Coffee Shop----------");
        printf("\n\n\t1. Login   ");
        printf("\n\t2. Sign Up ");
        printf("\n\nPlease enter 1 or 2: ");
        char choice = getchar();
        system("cls||clear");
    
        //put while loop to check
        switch (choice) {
        case '1':
            valid_choice = 1;
            system("cls||clear");
            login();
            break;
        case '2':
            valid_choice = 1;
            system("cls||clear");
            user_signup();
            break;
        default:
            printf("\nInvalid Number\n");
            break;
        }
    }

    return 0;
}

相关问题