C 只输入小数
我试图在简单的 C 应用程序中将输入限制为仅数字,但是我收到警告。我怀疑这与以下部分有关。版本一是正确的做事方式吗?谢谢。
for(i=0;i< strlen(string); i++)
{
if( string[i]<"0" || string[i]>"9")
valid= FALSE;
}
或者
for(i=0;i< strlen(string); i++)
{
if( string[i]<'0' || string[i]>'9')
valid= FALSE;
}
我的其余代码是
void main()
{
char number[4];
printf("Please enter a decimal number: ");
gets(number);
if (numeric(number))
printf("'%s' is a valid number\n", number);
else
printf("'%s' is an invalid number\n", number);
}
为了澄清我必须按照我正在做的练习给出的方式进行检查。谢谢。
I'm trying to restrict the input to only numerics in a simple C application however I get a warning. I suspect it's to do with the following segment. Is version one the proper way of doing things? Thanks.
for(i=0;i< strlen(string); i++)
{
if( string[i]<"0" || string[i]>"9")
valid= FALSE;
}
OR
for(i=0;i< strlen(string); i++)
{
if( string[i]<'0' || string[i]>'9')
valid= FALSE;
}
rest of my code is
void main()
{
char number[4];
printf("Please enter a decimal number: ");
gets(number);
if (numeric(number))
printf("'%s' is a valid number\n", number);
else
printf("'%s' is an invalid number\n", number);
}
To clarify I have to do the check in the fashion given according to the exercise I'm doing. Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
第一版是完全错误的。它进行指针比较,因为字符串文字会衰减为指针,并且字符会提升为
int
。第二个版本很接近,但您确实应该使用
中的isdigit
。顺便说一句,你知道
i
i
i
i
i
i
i
i
i
i
循环终止条件中的 strlen(string)
将线性时间算法变为二次时间算法?Version one is entirely wrong. It does pointer comparisons, because string literals decay to pointers and characters are promoted to
int
.Version two is close, though you should really use
isdigit
from<ctype.h>
.Btw., are you aware that
i < strlen(string)
in a loop termination condition turns linear-time algorithms into quadratic-time ones?你不能只使用 if (scanf ("%d", &n)==1) 或调用 strtol 吗?
Can't you just use
if (scanf ("%d", &n)==1)
or callstrtol
?