gpt4 book ai didi

c - 从用户那里读取号码

转载 作者:行者123 更新时间:2023-11-30 19:43:06 24 4
gpt4 key购买 nike

我想从用户那里读取一个正整数。如果用户输入其他内容,我想再次询问。当用户输入负数时我就这样做了。但是如果用户输入一个字符或者其他什么,我该怎么办?

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 == '\0') {
break; // valid
}
}
printf("Error message of your choice\n");
Prompt();
}

关于c - 从用户那里读取号码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30019899/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com