如何在 if 条件中区分零和未定义
How to distinguish zero from undefined in if condition?
int todayPrice
cout << "Enter the price of the item this year:n";
cin >> todayPrice;
if ( todayPrice == 0 ) {
throw DIVIDED_BY_ZERO;
} else if ( todayPrice < 0 ) {
throw LESS_THAN_ZERO;
} else if ( !todayPrice ) {
throw NOT_A_NUM;
}
如果用户输入零或字符串(我猜是未定义的),它将计算为"数字 == 0",并且它们都抛出DIVIDED_BY_ZERO异常。
如何区分 todayPrice 是未定义的(当用户输入字符串时)而不是 0??
如果用户输入的不是整数,则输入流将进入失败状态,您可以通过流进行检查:
if (std::cin >> todayPrice)
{
// Do your other checks
}
else
{
// User entered something that wasn't a valid integer
std::cout << "Not a valid integer inputn";
}
检查输入是否成功:
if (cin >> num)
相关文章:
- 在 Mac 上使用 CMAKE 将 FFTW 和 FFTWPP 链接到项目中时未定义的符号
- 尝试调用 .h 文件中定义的变量时出现变量未定义错误
- 在C++中使用内联方法时出现未定义的符号错误
- 在UE4中使用未定义类型'UTextBlock'
- C++ 中的编译错误:未定义对"主"的引用 collect2:错误:ld 返回 1 个退出状态
- 在 SVM-Struct 中未定义对 sqrt 的引用(已使用 -lm)
- 编译问题:在函数"_start"中:未定义对"主"的引用 collect2:错误:ld 返回 1 个退出状态
- Windows 链接器是否使用 LoadLibrary 解析 DLL 中未定义的符号?
- 如何修复C++中未定义的引用?
- "未定义对'WinMain@16'的引用"gcc 编辑器中的错误
- 对 CMake 中'cudaRegisterLinkedBinary'链接错误的未定义引用?
- C++ 中 dlsym 的未定义符号
- MacOS 上的 Xcode 11 项目不在一个函数中使用 sin 和 cos:未定义的符号"___sincosf_stret"
- QT C++中对全局变量的未定义引用
- OSX clang++:用于 cpp 文件中显式实例化模板的体系结构x86_64的未定义符号
- OpenCV 3.4.3 中对 'cv::String::d eallocate()' 错误的未定义引用
- CLion - 无法解决类中对构造函数的未定义引用
- 为什么我在 Windows API 中得到对 TextOut() 函数的未定义引用?
- CPP 程序中未定义的行为
- 在使用 GCC 4.8.5 构建的应用中对 cxx11 函数的未定义引用