[英]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);
// 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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.