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() 但它不起作用,請問有什么解決方案嗎?
uj5u.com熱心網友回復:
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);
也就是說,我建議您看一下fgetsand sscanf。它們通常是比scanf
uj5u.com熱心網友回復:
我認為最好將它作為字串接收并檢查所有字符是否都是數字。如果所有字符都是數字,它們會將它們轉換為 int
像這樣
number = number * 10 chars[n] - '0';
uj5u.com熱心網友回復:
scanf(" %d", &choice);無法處理轉換后的輸入超出int范圍的情況。這會導致未定義的行為。
使用scanf().
用于fgets()將一行用戶輸入讀入字串,然后進行驗證。
對于str2subrange(),請參閱為什么沒有strtoiin 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;
}
uj5u.com熱心網友回復:
該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);
uj5u.com熱心網友回復:
而不是遞回呼叫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;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/529922.html
標籤:C验证
