【发布时间】:2012-11-13 10:58:42
【问题描述】:
我遇到的问题是我想禁止用户在我的程序中放置字符而不是数字,并可选择打印“它已禁用”消息。它应该询问相同变量的值。我试图这样做:
scanf(" %[0-9]d",&x);
还有这个:
else
result = scanf("%*s");
但它仍然不起作用。我应该寻找什么?我搜索了互联网,但我只找到了使用 cin 的 C++ 解决方案,不幸的是它在 C 中根本不起作用。
【问题讨论】:
我遇到的问题是我想禁止用户在我的程序中放置字符而不是数字,并可选择打印“它已禁用”消息。它应该询问相同变量的值。我试图这样做:
scanf(" %[0-9]d",&x);
还有这个:
else
result = scanf("%*s");
但它仍然不起作用。我应该寻找什么?我搜索了互联网,但我只找到了使用 cin 的 C++ 解决方案,不幸的是它在 C 中根本不起作用。
【问题讨论】:
你可以试试这样的:
char c[SIZE];
int i;
// While the string is not a number
while(fgets(c, SIZE , stdin) && !isAllDigit(c));
isAllDigit 在哪里:
int isAllDigit(char *c){
int i;
for(i = 0; c[i] != '\0' && c[i] != '\n'; i++) // Verify if each char is a digit
if(!isdigit(c[i])) // if it this char is not a digit
return 0; // return "false"
return 1; // This means that the string is a number
}
【讨论】:
scanf 不再使用太多,因为它完全不适合键盘输入。现在的基本方案是循环执行 fgets() + validate + sscanf()。
【讨论】: