【发布时间】:2017-03-05 09:01:23
【问题描述】:
我有这个代码,但是当我输入一个超过整数值的值时它会打印垃圾。我实际上有 if 条件来检查范围。如何让它发挥作用?我知道这对你来说很容易。我只是在 C++ 中忘记了一些东西,我没有时间。
#include <iostream>
#include <typeinfo>
#include<cfloat>
#include<climits>
using namespace std;
int g1, g2;
string text = " year";
string text2 = " age";
int main() {
g1 = 2100000000000000000000000;
g2 = 16;
if (g1 < INT_MIN || g1 > INT_MAX) {
std::cout << "Please enter an integer";
} else {
std::cout << g1 << text;
std::cout << g2 << text2;
}
return 0;
}
【问题讨论】:
-
您正在检查
int是否小于INT_MIN。怎么可能? -
Jou 可以尝试解析为整数。如果返回错误,则不是整数,因为它包含无效字符,或者大于
INT_MAX或小于INT_MIN。 -
这闻起来像XY problem。您真正想要达到什么目的?
-
打开编译器警告并使用足够高的级别来获得类似
warning: overflow in implicit constant conversion
标签: c++