我有一个接受用户输入值的要求。它可以是整数或字符串。接受用户输入如下。
string strArg;
cout << "Enter price value " << endl;
std::getline(std::cin, strArg);
int input;
std::stringstream(strArg) >> input;
问题是我如何检查用户输入的是整数而不是字符串,即检查输入是否正确。我们如何在 C++ 中以可移植的方式做到这一点?因为在我的项目中不允许使用 Boost,因为我的经理不喜欢使用它:)
最佳答案
应该这样做:
#include <iostream>
#include <sstream>
#include <string>
int main(void)
{
std::cout << "input:" << std::endl;
std::string input;
std::getline(std::cin, input);
std::istringstream str(input);
int iv = 0;
// this checks that we've read in an int and we've consumed the entire input, else
// treat as string.
if (str >> iv && str.tellg() == input.length())
{
std::cout << "int: " << iv << std::endl;
}
else
{
std::cout << "string: " << input << std::endl;
}
return 0;
}
关于c++ - 在 C++ 中检查用户输入的正确值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5001993/