user3885399
user3885399

Reputation:

Why does this cause in infinite loop with chars but not doubles?

I feel like im doing something really silly wrong. I just want the program to tell the user when they are entering non-doubles, and continue to loop back to the cin where you enter a value.

I want the user to input any number. Then essential do this trivial math and repeat. Its working fine in that regard, the problem comes when some unexpected input like a char gets entered. Then the input somehow sends it into a loop where it loops the math problem, instead of just telling the user that they must type a number and looping back to cin type in a new number.

#include <iostream>
#include <cstdlib>

using std::cout; using std::cin; using std::endl;

long double domath(long double i)
{ 
     cout << i << "/" << 2 << "=" << i/2 << endl;    
     cout << i/2 << "*" << 10 << "=" << (i/2)*10 << endl << endl;   
     cout << 5 << "*" << i << "=" << 5*i << "\n\n";      
     return 0;
}

int main()
{

    long double in = 0;

    while(true)
    {
        cin >> in;         
        if (cin.fail()) {             
            in = char(int(in));  
        }           
        domath(in);
    }
    system("pause>nul");
    return 0;
}

Upvotes: 1

Views: 359

Answers (2)

HumbleWebDev
HumbleWebDev

Reputation: 575

Couldn't you try doing something like this?

int x;

if(std::cin >> x)
  doSomethingCool(x);
else
  std::cout << "Error, not a valid integer!" << std::endl;

Exit your loop on bad input.

I think this just feels more natural/looks cleaner than clearing the buffer and all the other jazz. Just my opinion.

if (cin >> x) - Why can you use that condition?

edit: Bul's answer is still a good one though.

Upvotes: 0

buld0zzr
buld0zzr

Reputation: 962

You don't clear the cin in case of fail, and it infinitely tries to parse wrong input to double, failing every time. You need to clear the buffer in case of error:

if (cin.fail()) {
    cin.clear();
    cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    in = char(int(in));
}

Also, can't understand what you're trying to achieve with

in = char(int(in));

in is a long double variable and will hold the last value you assigned to it, no need to "convert" it to do math.

Upvotes: 1

Related Questions