我现在正在试验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
。背后的逻辑是什么?你能指望什么?我想你的问题是合乎逻辑的。我建议你:
- 分别处理返回值和输入值
- 删除
exit()
语句,改用返回值。exit()
终止程序。 - 删除全局变量
- 如果上述内容无法帮助使用
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/