简体   繁体   English

C - scanf 变量,但它不是整数

[英]C - scanf variable while it is not an integer

I want my function to read my variable while it is not an integer.我希望我的函数在它不是整数时读取我的变量。 My teacher taught us to do it using the form var=scanf("%d", &x) and if it is a string, it will be equal to zero.我的老师教我们使用var=scanf("%d", &x)的形式来做,如果它是一个字符串,它将等于零。 However, when I enter a string, the while loop repeats without asking me to re-enter a value.但是,当我输入一个字符串时,while 循环会重复而不要求我重新输入一个值。

Here's my algorithm:这是我的算法:

int returnValue(int a, int b)
{
    int x, r;
    do{
        printf("Enter a value between %d and %d.\n", a, b);
        r=scanf("%d", &x);
    }while(x<a || x > b || r==0);
    return x;
}

If someone has any idea of the problem, it would be great.如果有人对这个问题有任何想法,那就太好了。

while loop repeats without asking me to re-enter a value. while 循环重复而不要求我重新输入值。

The non-numeric input that did not covert to an int remains in stdin for the next I/O operation.未转换为int的非数字输入保留在stdin以供下一个 I/O 操作使用。 Same offending input is read again each loop in OP's code. OP 代码中的每个循环都会再次读取相同的违规输入。 Code should read and discard the non-numeric input.代码应该读取并丢弃非数字输入。

I recommend to not use scanf() until you know why it is bad.我建议不要使用scanf()直到你知道它为什么不好。
In the meantime, use fgets() to read line of user input.在此期间,使用fgets()读取用户输入的线

int returnValue(int a, int b) {
  char buf[40];  // Suggest a size twice the expected max.
  int x, r;
  do {
    printf("Enter a value between %d and %d [inclusive].\n", a, b);
    if (fgets(buf, sizeof buf. stdin) == NULL) {
      fprintf(stderr, "End-of-file or input error\n");
      return INT_MIN;  // Or some other invalid value.    
    }
    int r = sscanf(buf, "%d", &x);  // or look into strtol() as a more robust solution
  } while(r != 1 || x < a || x > b); // test r first else x is undefined.
  return x;
}

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

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