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

How do I parse user input from the standard input stream?

本文关键字:用户 输入 标准输入流      更新时间:2023-10-16

我正在写一个非常简单的程序,我想从标准输入流(键盘)获得用户输入,然后根据我遇到的输入做一些事情。然而,问题是,有时输入将是一个数字(双),而有时则是一个字符串。我不确定我需要调用什么方法才能正确解析它(可能类似于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 ) ;
    } ...
}