这是我代码的一部分:
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);
}
现在它只能阻止用户输入负值,但是如何添加它以便它也阻止用户输入char?
答案 0 :(得分:5)
...阻止用户输入负值...
是不可能的。用户输入各种乱码。而是读取用户输入的行并解析它的正确性。使用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);
答案 1 :(得分:3)
但是如何添加它以便它也阻止用户输入char?
您无法阻止用户输入字符值。您可以做的是检查是否已成功扫描tktAdult
。
如果没有,请从stdin中清除所有内容:
bool valid = false;
while (true) {
...
if (scanf("%d", &TktAdult) != 1) {
int c;
while ((c = getchar()) != EOF && c != '\n');
} else {
break;
}
}
更好的选择是使用fgets()
,然后使用sscanf()
解析该行。
另见:Why does everyone say not to use scanf? What should I use instead?。
答案 2 :(得分:3)
// 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);
答案 3 :(得分: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'。)
答案 4 :(得分:0)
#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;
}