如何使程序只接受c中的正整数值 [英] how to get program to accept only positive integer values in c

查看:60
本文介绍了如何使程序只接受c中的正整数值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

writing a program that will be finding min, max, avg of values entered by user. Having trouble writing something that will check to make sure there are only postive integers entered and produce an error message. heres my for statement that is reading the input so far:

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

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

mind you I've been learning code for about 3 weeks and was just introduced to loops this week so my understanding is rudimentary at best!

推荐答案

首先,不要使用 scanf .如果 stdin 与它期望的不匹配,它会将其留在缓冲区中并继续重新读取相同的错误输入.调试非常令人沮丧.

First, don't use scanf. If stdin doesn't match what it expects it will leave it in the buffer and just keep rereading the same wrong input. It's very frustrating to debug.

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");
    }
}

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

Watch what happens when you feed it something that isn't a number. It just keeps trying to read the bad line over and over again.

$ ./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 仅识别整数.然后检查它是否为阳性.

Instead, use fgets to reliably read the whole line and sscanf to parse it. %f is for floats, decimal numbers. Use %d to recognize only integers. Then check if it's positive.

#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 值,或者没有更多输入为止.

Note that because the user might input bad values we can't use a simple for loop. Instead we loop until either we've read enough valid values, or there's no more input.

这篇关于如何使程序只接受c中的正整数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆