如何确保用户输入正数

时间:2015-04-26 08:41:02

标签: c

我这样做了,但遗憾的是它不起作用,当输入为char / string等时崩溃。

我该如何解决?

while((scanf("%d",&numOfDef) != 1 ) && (numOfDef>0 ))
{
  printf("not a pos num try again");
}

3 个答案:

答案 0 :(得分:0)

实际上,需要进行两项更改:while((scanf("%d",&numOfDef) >= 0 ) && !( numOfDef>0 ))

首先,将scanf的返回值与0进行比较,其次条件应为!( numOfDef>0 )( numOfDef<=0 )

scanf的返回值(来源:http://www.geeksforgeeks.org/g-fact-10/) :

  

在C中,printf()返回在输出上成功写入的字符数,scanf()返回成功读取的项目数。

代码的Ideone链接:http://ideone.com/TjtuDy

答案 1 :(得分:0)

numOfDef = 0;
while((scanf("%d",&numOfDef) != 1 ) || (numOfDef<=0 ))
{
  printf("not a pos num try again\n");
  int ch;
  while((ch=getchar())!= '\n' && ch != EOF);
  if(ch == EOF){
      numOfDef = 0;
      break;
  }
}
if(numOfDef == 0)
    puts("Processing was discontinued.");
...

答案 2 :(得分:0)

将输入作为字符串处理通常更容易,即使从用户那里获取数字输入,然后将字符串转换为数字:

#include<stdio.h>

int main (void) {

    char buf[32] = {0};
    int num = -1;

    while (num < 0) {
        printf (" Enter a positive number: ");
        if (scanf (" %[^\n]%*c", buf) == 1) {
            if (*buf < '0' || *buf > '9') continue;
            sscanf (buf, " %d", &num);
        }
    }

    printf ("\n You entered : %d\n\n", num);

    return 0;
}

<强>输出

$ ./bin/positive_entry
 Enter a positive number: --1--1 1--1
 Enter a positive number: #%@#&%$ u08$
 Enter a positive number:  wise guys^2
 Enter a positive number: -127
 Enter a positive number: -3
 Enter a positive number: a
 Enter a positive number: 2

 You entered : 2