C - 检查scanf读取的int是否在整数范围内 [英] C - Check that an int read by scanf is in the range of the integers
问题描述
我有这个代码使用scanf读取整数,并通过查看缓冲区来检查它是否实际上是一个整数。
I have got this code that reads an integer using scanf and checks if it is actually an integer by looking at the buffer.
int e_1;
char c[1];
// noNeedToCleanBuffer is used to avoid buffer cleaning the first time.
int noNeedToCleanBuffer = 1;
do {
// Clears the buffer.
if (!noNeedToCleanBuffer)
while ((c[0] = getchar()) != '\n') ;
noNeedToCleanBuffer = 0;
printf("Input an integer value: \n");
e_1 = scanf("%d", &n);
c[0] = getchar();
} while ((e_1 != 1 && c[0] != 10) || (e_1 == 1 && c[0] != 10));
但我无法弄清楚如何检查输入是否在INT_MIN和INT_MAX之间(我从limits.h中)。
However I cannot figure out how to check if the input is between INT_MIN and INT_MAX (I get these from limits.h).
我想把数字作为一个字符串,并将它与两个代表INT_MIN和INT_MAX的字符串进行比较,但由于我使用的是标准c99,我不允许使用atoi()或itoa()。
I was thinking of getting the number as a string and compare it with two strings that would represent INT_MIN and INT_MAX, but since I am using the standard c99 I am not allowed to use atoi() or itoa().
推荐答案
如果你真的只想检查存储它 -
If you really just want to check store it-
1.)存储长,然后检查
1.)Store in long and then check
2.)将数字存储在字符串中然后通过获取每个数字并存储在字符串中然后使用将INT_MAX转换为字符串strcmp()
2.)Store the number in string then convert the INT_MAX into a string by getting each digit and storing in string and then using strcmp()
num = INT_MAX;
i = 0;
while(num != 0){
str[i] = num % 10;
num = num / 10;
i++;
}
此字符串中的数字相反,您可以很容易地将其反转一个简单的循环
The number would be opposite in this string you can get it reversed quite easily by a simple loop
然后使用strcmp();
Then use strcmp();
这篇关于C - 检查scanf读取的int是否在整数范围内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!