我编写的 C++ 函数遇到了一个恼人的问题,该函数的目的是验证用户输入。该函数读取用户输入,验证它是否是数字,如果是,则验证它是否在 [min, max] 范围内。
当我使用无符号类型(如 size_t
)调用模板函数并且输入为负数时,就会出现问题。字符串流将字符串转换为类似 4294967291 的内容。我可以看到程序正在将数据转换为接近无符号数据类型最大值(在 numeric_limits header 中定义)的值,但我的问题是为什么,因为 if
语句应在 sstream >> value
处停止?
我的代码:
template <class T>
T getNumberInput(std::string prompt, T min, T max) {
std::string input;
T value;
while (true) {
try {
std::cout << prompt;
std::cin.clear();
std::getline(std::cin, input);
std::stringstream sstream(input);
if (input.empty()) {
throw EmptyInput<std::string>(input);
} else if (sstream >> value && value >= min && value <= max) {
std::cout << std::endl;
return value;
} else {
throw InvalidInput<std::string>(input);
}
} catch (EmptyInput<std::string> & emptyInput) {
std::cout << "O campo não pode ser vazio!\n" << std::endl;
} catch (InvalidInput<std::string> & invalidInput){
std::cout << "Tipo de dados inválido!\n" << std::endl;
}
}
}
感谢您的宝贵时间!
最佳答案
在涉及具有 n 个值位的 unsigned
类型的 C++ 算术中,保证模 2^n。这意味着通过添加或减去 2^n 的适当倍数,任何结果都将返回到 0 到 2^n-1 的范围内。在 C 语言中也是如此。
因此您需要检查输入的减号,或添加一些其他检查。
顺便说一句,您的 if
与 >>
和 &&
对我的坏代码计产生了一些影响。我永远记不起 >>
与 &&
的运算符优先级。我想如果它编译了它一定没问题,因为 >>
不能在右侧取值。检查...好的,但我会使用括号来澄清这一点。
此外,在代码结构上,将交互式输入与输入检查分开是一个好主意。例如,您可以在 GUI 程序中使用任何代码并从编辑字段输入吗?不,不是这样的......
干杯,
关于c++ - 将 string 类型转换为 unsigned int 时出现故障,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4151340/