如何从标准输入流中解析用户输入
How do I parse user input from the standard input stream?
我正在写一个非常简单的程序,我想从标准输入流(键盘)获得用户输入,然后根据我遇到的输入做一些事情。然而,问题是,有时输入将是一个数字(双),而有时则是一个字符串。我不确定我需要调用什么方法才能正确解析它(可能类似于java中的Integer.parseInt)。
以下是我想做的一些伪代码:
cin >> input
if(input is equal to "p") call methodA;
else if(input is a number) call methodB;
else call methodC;
我认为这就是您所需要的:
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
void a(string& s){ cout << "A " << s << endl; }
void b(double d){ cout << "B " << d << endl; }
void c(string& s){ cout << "C " << s << endl; }
int main()
{
std::string input;
cin >> input;
if (input == "p")
a(input);
else
{
istringstream is;
is.str(input);
double d = 0;
is >> d;
if (d != 0)
b(d);
else
c(input);
}
return 0;
}
希望这能有所帮助;)
std::string input;
std::cin >> input;
if(input =="p") f();
else if(is_number(input)) g();
else h();
现在实现is_number()
功能:
bool is_number(std::string const & s)
{
//if all the characters in s, are digits, then return true;
//else if all the characters, except one, in s are digits, and there is exactly one dot, then return true;
//else return false
}
自己实现这个功能,因为这似乎是家庭作业。您也可以考虑这样的情况:数字可能以符号+
或-
开头。
我使用的通常解决方案是将输入作为一行读取(使用std::getline
而不是>>
),并像在任何情况下一样解析它语言;CCD_ 6在这里非常有用;如果你确信你可以指望C++11,它是std::regex
(我认为它几乎是与Boost相同)。所以你最终会得到这样的东西:
std::string line;
if ( ! std::getline( std::cin, line ) ) {
// Error reading line (maybe EOF).
} else {
if ( regex_match( line, firstFormat) ) {
processFirstFormat( line );
} else if ( regex_match( line, secondFormat) ) {
processSecondFormat( line ) ;
} ...
}
相关文章:
- C++如何通过用户输入删除列表元素
- 如何使用用户输入在C++中正确填充2D数组
- C++MySQL C api用户输入行
- 如何只允许用户输入正整数
- C++如何计算用户输入的数字中的偶数位数
- 通过for循环使用用户输入填充列表
- 在C++中,我如何接受不同于同一行的用户输入
- 如果用户输入无效,如何使用字符串变量-C++重复输入命令
- 显示基于用户输入的整数的字符
- 根据用户输入用字母填充矢量,并将"开始"和"结束"放在四肢
- 我试图制作一个程序,要求用户输入问题和答案,但程序循环不正确
- 打印时有二叉树问题.用户输入不打印任何内容
- C ++奇怪的数组由用户输入
- 如何允许大写和小写用户输入?
- C++读取用户输入而不按回车键(Mac OS X),与Turbo Pascal中的读取键相同
- 如何存储用户输入的所有数据,然后在他们想要查看所有数据时显示它们
- 如何使用用户输入变量制作二维数组?
- 用户输入字符串的文件附加问题..C++
- 遇到此问题时遇到困难:允许用户输入数组的值并使用 for,而循环也输出输入的最大数字
- 如何使用递归循环我的代码(当用户输入无效输入时,它会再次提示他们)?