c - 如果在 C 中使用 scanf 输入字符,如何打印错误

标签 c char scanf exit-code

我现在正在试验c,这个程序应该让用户输入一个10-100范围内的数字,如果他输入的任何内容不满足这些条件,程序将退出并显示错误代码1.任何满足条件的东西,程序都会以0退出。下面是到目前为止的代码,但拒绝在字符检测时打印正确的错误。

#include <stdio.h>
#include <stdlib.h>


int intGet(int ,int);
int error();
int userIn;
char x;

int main(void) {
    printf("Enter a number in between [10 -­100]: \n");
    x = scanf("%d", &userIn);
    intGet(x, userIn);

    return EXIT_SUCCESS;
}

int intGet(int min,int max ) {
    min = 10;
    max = 100;

    x = userIn;
    if ((x < min) || (x > max)) {
        printf("Input out of Range\n");
        exit(EXIT_FAILURE);
    } else if (x == 0) {
        printf("Incorrect input format\n");
        exit(EXIT_FAILURE);
    } else {
        printf("Read %d\n", userIn);
        exit(EXIT_SUCCESS);
    }
}

int error() {

}

最佳答案

目前尚不清楚您的问题是什么。您预计会出现什么错误?

您需要整理您的代码。事情很少。 scanf 返回 int 值 - 分配的输入项的数量。您将返回值分配给char x。然后将输入值分配给x。背后的逻辑是什么?你能指望什么?我想你的问题是合乎逻辑的。我建议你:

  1. 分别处理返回值和输入值
  2. 删除 exit() 语句,改用返回值。 exit() 终止程序。
  3. 删除全局变量
  4. 如果上述内容无法帮助使用 printf 查看正在处理的内容

示例:

int main(void) {
    printf("Enter a number in between [10 -­100]:\n");
    int userIn;
    int x = scanf("%d", &userIn);

    // for debug
    printf("Scanned: %d, returned: %d", x, userIn);

    int result = intGet(x, userIn);
    // analyse the result here
    switch (result) {
        case RES_SUCCESS:
           return SUCCESS;
        case ...
    }
}


int intGet(int x, int value) {
    int const min = 10;
    int const max = 100;

    if (x != 1) {
        return RES_ERROR_NO_INPUT;
    }

    if (value < min || value > max) {
        return RES_ERROR_OUT_OF_RANGE;
    }

    return RES_SUCCESS;
}

关于c - 如果在 C 中使用 scanf 输入字符,如何打印错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18840402/

相关文章:

objective-c - 如何正确定义常量

c - 在 C 中分割命令行参数

const char * 与 == 比较

c - C 中用字符串初始化的静态 char 数组

c - fscanf 无法正确读取 float

c - 成员(member)运营商 : How to use "my_var" actual value in "my_struct->my_var"?

c - 将参数放入 char 数组,代码解释

c - 使用 fscanf() 读取一行

c - sscanf 在 %[^-]s 匹配后缺少一个字符串

我可以通过发送带有 NULL 位图句柄的 STM_SETIMAGE 消息来清除静态控件中的位图吗