Caotic errors

For example, I've this code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#include <iostream>
class TipoMoeda
{
    public:

        public:
             struct real
    {
    double valor;
    void ConverterParaDolar()
    {
        valor = valor/2.11;
    }
            double operator=(const double& valor_a_definir)
        {
            valor = valor_a_definir;
        }
    };

    struct dolar
    {
        public:
        double valor;
        void ConverterParaReal()
        {
            valor = valor*2.11;
        }
        double operator=(const double& valor_a_definir)
        {
            valor = valor_a_definir;
        }

    };
};



int main()
{
    int tipo;
    double quantia;
    MainLoop:
    std::cout<<"Selecione o tipo conversao:\n1. Reais - Dolares\n2. Dolares - Reais \n\nEscolha: ";
    std::cin>>tipo;

    if (tipo==1)
    {
        TipoMoeda::real Dinheiro;
        std::cout<<std::endl<<"Entre com a quantia: ";
        std::cin>>quantia;
        Dinheiro = quantia;
        Dinheiro.ConverterParaDolar();
        std::cout<<"Entrada: "<<quantia<<" reais\t Saida: "<<Dinheiro.valor<<" dolares\n\n";
        goto MainLoop;

    }
    if (tipo==2)
    {
        TipoMoeda::dolar Dinheiro;
        std::cout<<std::endl<<"Entre com a quantia: ";
        std::cin>>quantia;
        Dinheiro = quantia;
        Dinheiro.ConverterParaReal();
        std::cout<<"Entrada: "<<quantia<<" dolares\t Saida: "<<Dinheiro.valor<<" reais\n\n";
        goto MainLoop;
    }
    else
    {
        std::cout<<"Escolha invalida\n\n\n";
        goto MainLoop;
    }
}


But if I enter "kkkkkkkkkkk" in 'tipo', the else field will be repeted infinitely. How can I make my program safier?

Thanks.
The default of structs is public, so you don't need to explicitly state public. Also goto statements are not recommended in c++. You should reserve that for programming in assembly. You should be able to structure your program in such a way that it flows from one state to another by either using loops or function calls. Using gotos is just an excuse to get away with bad code structure.

To solve your problem, anywhere you use cin >>, below that put:

1
2
3
#include <iostream>
#include <limits>
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');


This is because cin ignores new lines, so it leaves it in the input buffer when it finds a newline character. But subsequent calls to cin keeps trying to read more input but upon encountering the newline, it just stops reading. The above method clears the newline character.
Last edited on
Thanks, and I'll use while loop. Where do I use this cin.ignore?
Thanks.
Topic archived. No new replies allowed.