Christiano19
Christiano19

Reputation: 21

Strange trouble with a loop in c++

I've just started studying programming at school. I've been having a problem getting my code to reject a non-numeric cin from the user. I figured out a way to do it but now this weird thing is happening when I put a number in I have to insert valid input 3 times before it will clear through the loop and go on to the next part of the program.

// Amount to be converted

if (exchangeRate == JAPANESE_EXCHANGE_RATE)
{
    cout << "How many " << currencyName << " do you need a conversion for?" << '\n' << '\n';
}
else
{
    cout << "How many " << currencyName << "s do you need a conversion for?" << '\n' << '\n';
}
do
{
    cin >> conversionAmount;
    cout << '\n' << '\n';
    if (conversionAmount > -1)
    {
        cout << '\n'; // nothing needs to be done, the number will be accepted and proccessed;
    }
    else if (!(cin >> conversionAmount) || conversionAmount < 0)
    {
        cin.clear();
        cin.ignore(10000000000000, '\n');
        cout << "That value does not work; try again";
        cout << '\n' << '\n';
    }
}
while (!(cin >> conversionAmount));

This is just the part of the code that is messing up; it runs perfectly except for the strange way I have to get it out of the loop. If you need any more of the code Ill happily post it. I just started studying programming so if you could also explain the logic behind my mistake it would help me greatly.

Upvotes: 0

Views: 83

Answers (1)

MehrZ
MehrZ

Reputation: 61

Every time you execute cin >> conversionAmount your input stream (cin) is waiting for an input. If you look at your code you have 4 cin >> conversionAmount in your loop. So you need to enter your input 4 times to go to the next iteration.

However, overall it is preferred to use stringstreams rather than reading directly from cin. look at this Tutorial

As you can see, extracting from cin seems to make the task of getting input from the standard input pretty simple and straightforward. But this method also has a big drawback. What happens in the example above if the user enters something else that cannot be interpreted as an integer? Well, in this case, the extraction operation fails. And this, by default, lets the program continue without setting a value for variable i, producing undetermined results if the value of i is used later.

This is very poor program behavior. Most programs are expected to behave in an expected manner no matter what the user types, handling invalid values appropriately. Only very simple programs should rely on values extracted directly from cin without further checking. A little later we will see how stringstreams can be used to have better control over user input.

Upvotes: 1

Related Questions