简体   繁体   English

C-如何检查是否输入了号码

[英]C - How to check if number entered

How to simply and correctly check if user enters a number and not a char or string in C language? 如何简单,正确地检查用户是否输入数字而不是C语言中的字符或字符串? I've tried to write some loops containing: 我试图写一些包含以下内容的循环:

if (scanf("%d",&number)=1) 

but they never work or end. 但他们永远不会工作或结束。 The loop should end when a number is entered. 输入数字后,循环应结束。

It should be 它应该是

if (scanf("%d", &number) == 1) // Notice the two ='s, not just one

A single = is the assignment operator, a double == is the equality test. 一个=是赋值运算符,一个==是相等检验。

I think you want this: 我想你想要这个:

for (scanf(" %d", &number); (number < -100 || number > 100); scanf(" %d", &number)) {
    printf("you didn't enter a valid number, try again >");
}

Your line should simply be: if (scanf("%d",&number)){ 您的行应该简单地是: if (scanf("%d",&number)){

If anything other than a number is entered, it will result in: if(0){ , instead of if(1){ 如果输入的不是数字,则结果为: if(0){ ,而不是if(1){

Does this suit your context: 这是否适合您的情况:

char ch;int g;
for(ch=getc(stdin);isalpha(ch);ch=getc(stdin))
{
printf("\nenter numbers only");
while(isalpha(getc(stdin))){}
}
ungetc(ch,stdin);
scanf("%d",&g);
printf("number entered  %d",g);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM