如何解析标准输入流中的用户输入?

时间:2012-01-31 16:45:37

标签: c++ input

我正在写一个非常简单的程序,我希望从标准输入流(键盘)获取用户输入,然后根据我遇到的输入做一些事情。然而,问题是有时输入将是一个数字(双倍),而其他输入将是一个字符串。我不确定为了正确解析它需要什么方法调用(也许类似于java中的Integer.parseInt)。

以下是我想做的一些pseduocode:

cin >> input
if(input is equal to "p") call methodA;
else if(input is a number) call methodB;
else call methodC;

3 个答案:

答案 0 :(得分:3)

我认为这就是你所需要的:

#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;
}

希望这会有所帮助;)

答案 1 :(得分: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
}

自己实现此功能,因为它似乎是功课。您也可以考虑使用符号+-开头的案例。

答案 2 :(得分:0)

我使用的常用解决方案是将输入读作一行(使用 std::getline而不是>>),并按照我的意愿解析它 语言 - boost::regex在这里非常有用;如果你确定的话 你可以指望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 ) ;
    } ...
}