检查 C++ 中用户输入的正确值
我有一个接受用户输入值的要求。它可以是整数或字符串。接受用户输入如下。
string strArg;
cout << "Enter price value " << endl;
std::getline(std::cin, strArg);
int input;
std::stringstream(strArg) >> input;
问题是我如何检查用户是否输入了整数而不是字符串,即检查是否正确输入。我们如何在 C++ 中以可移植的方式做到这一点?正如在我的项目中不允许使用 Boost,因为我的经理不高兴使用它:)
I have a requirment that accepts values from user input. It can be integers or strings. User input is accepted as below.
string strArg;
cout << "Enter price value " << endl;
std::getline(std::cin, strArg);
int input;
std::stringstream(strArg) >> input;
Question is how do i check user has entered integer, rather than string, i.e., check for right input. How can we do this in portable way in C++? As in my project Boost is not allowed as my manager is not happy in using it:)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
没有真正的理由要通过字符串流,除非如果用户输入无效的内容,您不需要清除它,而且您可以将其回显给他们。
如果您允许用户输入整数或字符串,但只是在输入时表现不同是一个字符串,你当然可以使用 istringstream。
请注意,您可能希望在读取数字后检查流是否为空,以防用户输入 123XYZ,如果您只是流式传输,则将被视为“有效”,因为它以整数开头。
There is no real reason to go through stringstream except you do not need to clear it if the user enters something invalid, plus you can echo it back to them..
If you allow the user to enter integers or strings but just behave differently when it is a string you can of course use istringstream.
Note that you may wish to check your stream is empty after reading the number in case the user entered 123XYZ which if you just streamed in would be considered "valid" as it starts with an integer.
像这样的事情应该做:
Something like this ought to do:
使用 std::stringstream 和运算符>> 并检查如果转换成功。
像这样的东西:
Use std::stringstream and operator>> and check if the conversion was successful.
Something like this:
boost::lexical_cast 与执行以下操作大致相同:
boost::lexical_cast is apprximately the same as doing:
您可以使用正则表达式来检查它。据我所知,新的C++标准支持正则表达式
You may use regular expressions to check it. As far as I know, new C++ standart has support of regular expressions