¿Cómo analizo la entrada del usuario desde el flujo de entrada estándar?

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;

preguntado el 31 de enero de 12 a las 16:01

¿Qué es? input? char or std::string? -

I'm not sure...whatever would make this program easiest to implement...So string I suppose -

3 Respuestas

Creo que esto es lo que necesitas:

#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")
        istringstream is;
        double d = 0;
        is >> d;
        if (d != 0)
    return 0;

Espero que esto ayude ;)

Respondido el 31 de enero de 12 a las 20:01

std::string input;
std::cin >> input;
if(input =="p") f();
else if(is_number(input)) g();
else h();

Ahora implementar is_number() función:

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

Implement this function yourself, as it seems to be homework. You can also consider case like the number may begin with sign + or -.

Respondido el 31 de enero de 12 a las 20:01

The usual solution I use is to read the input as a line (using std::getline más bien que >>), and parse it as I would in any language—boost::regex is very useful here; if you are sure that you can count on C++11, it's std::regex (which I think is almost identical to Boost). So you end up with something like:

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 ) ;
    } ...

Respondido el 31 de enero de 12 a las 21:01

if( !std::string( std::cin, line ) )? Te refieres a if (! std::getline( std::cin, line )? - Nawaz

@Nawaz Definitely. I'll edit the post to fix it. (I think that's called a thinko. Rather like a typo, but on a bigger scale.) - James Kanze

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.