String and double data entry

Asked

Viewed 94 times

0

I’m in a project to implement a C++ calculator that uses variables. Thus, if I define a variable x = 5, and type x 2 then returns me the value of 25. For this, I have to store the variable name and the corresponding value. The user would type a name or a double and depending on the input, store in value or name. There’s my difficulty.

I am trying to input C++ data with the use of class and operator overload. However, I cannot do this. I have a class called "variable":

class variavel
{
    public:
        std::string nome;
        double valor;
        friend std::istream& operator>> (std::istream& os, variavel &v);
};

What I want to do is something like:

std::istream& operator>> (std::istream& os, variavel &v)
{
    os >> v.nome;
    try
    {
        v.valor = ConverteParaDouble(v.nome); /* lança uma exceção se não for um numero */
        v.nome = ""; /* nao executa se lançar a exceção */
    }
    catch(excecao &e) /* captura a exceção */
    {
        /* Outros comandos */
    }
}

However, I don’t know how to do this, be it convert(I tried to use atoi, stod) is to make the exception. For the stod documentation(click here), it would be necessary, but always when I put the code:

std::istream& operator>> (std::istream& os, variavel &v)
{
    os >> v.nome;
    try
    {
        v.valor = std::stod(v.nome);
        v.nome = "";
    }
    catch(const std::invalid_argument& ia)
    {
        v.nome = "deu ruim";    
    }
}

But every time I try to compile, he says stod is not in the std. How do you fix it?

  • You’ve included the library iostream?

  • Yes, all inputs are working normally. In addition it includes sstream and string

  • 1

    In relation to stod it only exists from c++11, so please confirm that you are using that version otherwise add to flag compilation -std=c++11. And confirm that you have the options available in the compiler guide here to the mingw

  • It worked. Thank you!

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.