我想阅读用户的正整数。如果用户进入其他内容,我想再次询问。当用户输入负数时,我做到了。但是,如果用户进入角色或其他任何东西,我该怎么办?
int main (){
int takennumber;
int number,multiplication,divisor,result,total=0;
printf("Please,enter a integer number: ");
scanf("%d",&takennumber);
for(;takennumber<=0;)
{
printf("Wrong value! Please reenter: ");
scanf("%d",&takennumber);
}
如果您想完全控制输入处理(假设您只需要基础10),为什么不蛮力迫使它:
char buf[BUFSIZ], *p = buf;
char *retPtr;
unsigned long val;
Prompt();
while(fgets(buf, sizeof(buf)-1, stdin) {
p = buf;
while(isspace(*p)) p++);
errno = 0; /* just in case errno isn't cleared in strtoul - may not be needed */
/* strtoul used instead of strtol, to disallow negative number */
val = strtoul(p, &retPtr, 10); /* 10 assumes base 10 only */
/* strtoul returns value AND there no failure condition, we are good */
if (errno == 0 || (val == LONG_MIN || val == LONG_MAX)) {
/* See if anything follows the number on the line */
if (*retPtr == 'n' || *retPtr == ' ') {
break; // valid
}
}
printf("Error message of your choicen");
Prompt();
}
scanf
返回成功扫描值的数量。如果您尝试扫描int
,但是用户输入char
,则scanf
将返回0。您应该将呼叫转移到scanf
中,并检查其返回值:
printf("Enter a positive integer: ");
while (scanf("%d", &takennumber) < 1 || takennumber <= 0)
printf("Wrong value! Please reenter: ");