如何使程序仅接受c中的正整数值

时间:2018-10-11 23:30:10

标签: c loops

编写一个程序,该程序将查找用户输入的最小值,最大值,平均值。在编写某些东西时遇到麻烦,它将检查以确保仅输入正整数并产生错误消息。到目前为止,这是我的for语句,正在读取输入内容:

  for (int value = 0; value <= numofvals; ++value) {
      printf("Value %d: %f\n", value, val_input);
      scanf("%f", &val_input);
  }

请注意,我已经学习了大约3周的代码,本周刚被介绍到循环中,所以我的理解充其量只是基本内容!

3 个答案:

答案 0 :(得分:2)

首先,don't use scanf。如果stdin与期望值不符,它将保留在缓冲区中,而只是继续重新读取相同的错误输入。调试非常令人沮丧。

const int max_values = 10;

for (int i = 0; i <= max_values; i++) {
    int value;
    if( scanf("%d", &value) == 1 ) {
        printf("Got %d\n", value);
    }
    else {
        fprintf(stderr, "I don't recognize that as a number.\n");
    }
}

观看当您输入非数字内容时会发生什么。它只是不断尝试一遍又一遍地读取坏线。

$ ./test
1
Got 1
2
Got 2
3
Got 3
foo
I don't recognize that as a number.
I don't recognize that as a number.
I don't recognize that as a number.
I don't recognize that as a number.
I don't recognize that as a number.
I don't recognize that as a number.
I don't recognize that as a number.
I don't recognize that as a number.

相反,使用fgets可靠地读取整行,并使用sscanf对其进行解析。 %f用于浮点数,十进制数字。使用%d仅识别整数。然后检查它是否为阳性。

#include <stdio.h>

int main() {
    const size_t max_values = 10;
    int values[max_values];
    char buf[1024];

    size_t i = 0;
    while(
        // Keep reading until we have enough values.
        (i < max_values) &&
        // Read the line, but stop if there's no more input.
        (fgets(buf, sizeof(buf), stdin) != NULL)
    ) {
        int value;

        // Parse the line as an integer.
        // If it doesn't parse, tell the user and skip to the next line.
        if( sscanf(buf, "%d", &value) != 1 ) {
            fprintf(stderr, "I don't recognize that as a number.\n");
            continue;
        }

        // Check if it's a positive integer.
        // If it isn't, tell the user and skip to the next line.
        if( value < 0 ) {
            fprintf(stderr, "Only positive integers, please.\n");
            continue;
        }

        // We got this far, it must be a positive integer!
        // Assign it and increment our position in the array.
        values[i] = value;
        i++;
    }

    // Print the array.
    for( i = 0; i < max_values; i++ ) {
        printf("%d\n", values[i]);
    }
}

请注意,因为用户可能输入了错误的值,所以我们不能使用简单的for循环。取而代之的是,我们循环执行,直到读取了足够的 valid 值,或者没有更多输入为止。

答案 1 :(得分:1)

类似这样的简单方法可能对您有用:

int n;
int ret;

for (;;) {
    ret = scanf("%d", &n);

    if (ret == EOF)
        break;

    if (ret != 1) {
        puts("Not an integer");
        for (;;)
            if (getchar() == '\n')
                break;
        continue;
    }

    if (n < 0) {
        puts("Not a positive integer");
        continue;
    }

    printf("Correct value %d\n", n);

    /* Do your min/max/avg calculation */
}

/* Print your results here */

这只是一个示例,并假设您不需要读取浮点数,然后检查它们是否为整数以及其他一些内容。但是对于初学者来说,它很简单,您可以在它之上进行工作。

要打破循环,您需要传递EOF(在Linux / macOS终端中通常为 Ctrl + D ,在Windows中为 Ctrl + Z )。

答案 2 :(得分:-2)

一个简单而便携的解决方案

#include <limits.h>
#include <stdio.h>
int get_positive_number() {
  char buff[1024];
  int value, ch;
  while (1) {
    printf("Enter positive number: ");
    if (fgets(buff, 1023, stdin) == NULL) {
      printf("Incorrect Input\n");
      // Portable way to empty input buffer
      while ((ch = getchar()) != '\n' && ch != EOF)
        ;
      continue;
    }
    if (sscanf(buff, "%d", &value) != 1 || value < 0) {
      printf("Please enter a valid input\n");
    } else {
      break;
    }
  }
  return value;
}
void solution() {
  // Handling malformed input
  // Memory Efficient (without using array to store values)
  int n;
  int min = INT_MAX;
  int max = INT_MIN;
  double avg = 0;
  printf("Enter number of elements: ");
  scanf("%d", &n);
  getc(stdin);
  int value;
  for (int i = 0; i < n; i++) {
    value = get_positive_number();
    if (value > 0) {
      if (min > value) {
        min = value;
      }
      if (max < value) {
        max = value;
      }
      avg += value;
    }
  }
  avg = avg / n;
  printf("Min = %d\nMax = %d\nAverage = %lf\n", min, max, avg);
}
int main() {
  solution();
  return 0;
}
  • 输出:


Enter number of elements: 3
Enter positive number: 1
Enter positive number: 2
Enter positive number: a
Please enter a valid input
Enter positive number: -1
Please enter a valid input
Enter positive number: 1
Min = 1
Max = 2
Average = 1.333333