如何从标准输入流解析用户输入?
我正在编写一个非常简单的程序,我想从标准输入流(键盘)获取用户输入,然后根据我遇到的输入执行某些操作。然而,问题是有时输入是数字(双精度),而有时输入是字符串。我不确定我需要调用什么方法才能正确解析它(可能类似于java中的 Integer.parseInt )。
这是我想做的一些伪代码:
cin >> input
if(input is equal to "p") call methodA;
else if(input is a number) call methodB;
else call methodC;
I'm writing a very simple program where I want to get user input from the standard input stream (keyboard) and then do something based on what input I encountered. However, the problem is that sometimes the input will be a number (double) while othertimes it'll be a string. I'm not sure exactly what methods calls I need in order to parse it properly (perhaps something similar to Integer.parseInt in java).
Here is some pseduocode of what I would like to do:
cin >> input
if(input is equal to "p") call methodA;
else if(input is a number) call methodB;
else call methodC;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为这就是您所需要的:
希望这会有所帮助;)
I think this is what you need:
Hope this helps ;)
现在实现 is_number() 函数:
自己实现这个函数,因为它看起来像是家庭作业。您还可以考虑数字可能以符号
+
或-
开头的情况。Now implement
is_number()
function:Implement this function yourself, as it seems to be homework. You can also consider case like the number may begin with sign
+
or-
.我通常使用的解决方案是将输入读取为一行(使用
std::getline
而不是>>
),并像我在任何情况下一样解析它语言——
boost::regex
在这里非常有用;如果你确定你可以依靠 C++11,它是
std::regex
(我认为这几乎是与 Boost 相同)。所以你最终会得到类似的结果:
The usual solution I use is to read the input as a line (using
std::getline
rather than>>
), and parse it as I would in anylanguage—
boost::regex
is very useful here; if you are sure thatyou can count on C++11, it's
std::regex
(which I think is almostidentical to Boost). So you end up with something like: