所以我看到很多人问这个问题,但网络上并没有很多可靠的答案。大多数只是检查一个整数是否被放置在一个字符串的位置,但是如果输入了一个 float ,那么它会截断下半部分,或者如果插入了整数和字符,它会截断字符。我需要帮助编写一段代码来检查用户输入并要求用户重试他的输入是否无效或有效/无效的组合。我认为基本的想法是制作一个字符串,这样它就可以接受任何东西,然后使用 sstream 进行操作,如果输入是合法的,然后返回到 int,但我无法真正设法检查其他部分。如果有人遇到这个或者可以帮助我,请将我链接到它。当我清楚地知道要做什么时,我会发布我的代码。
最佳答案
假设您不能使用boost::lexical_cast
,您可以编写自己的版本:
#include <sstream>
#include <iostream>
#include <stdexcept>
#include <cstdlib>
template <class T1, class T2>
T1 lexical_cast(const T2& t2)
{
std::stringstream s;
s << t2;
T1 t1;
if(s >> std::noskipws >> t1 && s.eof()) {
// it worked, return result
return t1;
} else {
// It failed, do something else:
// maybe throw an exception:
throw std::runtime_error("bad conversion");
// maybe return zero:
return T1();
// maybe do something drastic:
exit(1);
}
}
int main() {
std::string smin, smax;
int imin, imax;
while(std::cout << "Enter min and max: " && std::cin >> smin >> smax) {
try {
imin = lexical_cast<int>(smin);
imax = lexical_cast<int>(smax);
break;
} catch(std::runtime_error&) {
std::cout << "Try again: ";
continue;
}
}
if(std::cin) {
std::cout << "Thanks!\n";
} else {
std::cout << "Sorry. Goodbye\n";
exit(1);
}
}
关于c++ - 在 C++ 中检查合法的整数输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15275097/