我正在使用一个函数来检查我的输入是否只是一个整数。
int input;
while (true)
{
std::cin >> input;
if (!std::cin)
{
std::cout << "Bad Format. Please Insert an integer! " << std::endl;
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
continue;
}
else
return input;
}
但是当输入一个整数后跟一个字符的时候, 例如 3s输入的整数被接受,并打印出信息。
我怎样才能保证这样的格式的输入不会被接受,也不能保证这样的格式的输入不会被接受。4s 5所以,当整数出现在空格之后。
之所以会出现这种情况,是因为在c++中,chars在ascii表中是由其数值来表示的,你可以试试这样的正则表达式。
#include <regex>
#include <string>
std::string str;
std::regex regex_int("-?[0-9]");
while (true)
{
std::cin >> str;
if (regex_match(str, regex_int))
{
int num = std::stoi(str);
//do sth
break;
}
}
没有必要用正则表达式来重复验证... std::stoi
确实如此。只要用 std::stoi
:
std::string input;
std::cin >> input;
std::size_t end;
int result = std::stoi(input, &end);
if (end != input.size())
// error