John
John

Reputation: 55

C++ program quits after inputing double when int required. How to fix?

I have an assignment in which i have to make a program which takes the user input (natural number is required) and then prints out the reverse number. The program does that just fine however i also have to make sure that the program doesn't give me any errors when inputing values which aren't natural numbers. The program quits if i enter a double values or if i enter numbers followed by characters. In the rest of the cases the program works just fine. What could be causing these problems?

int number;
char x = 'c';
while (x == 'c') {
    cout << "Enter a number\n";
    cin >> number;
    while (!(cin.good()) || number < 1 || floor(number) != number) {
        cin.clear();
        cin.ignore(256,'\n');
        cout << "Try again.\n";
        cin >> number;
    }
    string reverse;
    stringstream convert; 
    convert << number;
    reverse = convert.str();
    reverse = string (reverse.rbegin(),reverse.rend());
    cout << "The reverse number for number " << number << " is " << reverse << endl;
    cout << "If you want to continue using the program enter 'c',\nif you want to close the program enter anythin else\n";
    cin >> x;
    }

Upvotes: 1

Views: 499

Answers (3)

AndersK
AndersK

Reputation: 36102

IMHO : In order to meet your assignment you need to first read the number as a string then you may want to check if the number is a natural number i.e. check if there is a '.' in the string, if not then do what you did before otherwise give an error message.

Upvotes: 0

PiotrNycz
PiotrNycz

Reputation: 24412

It is because with let say 123.456 your program reads 123 as int. Then reverses it then expects char x == 'c' but gets dot ..

Read std::string from std::cin after that check if it is int.

std::string reverse;
std::cin >> reverse;

std::istringstream test(reverse);
int value; std::string rest;
if (!(test >> value) || (test >> rest)) // must read int but nothing more
{
  prompt for new value
} 

Upvotes: 1

Jason
Jason

Reputation: 32520

I would actually take double as the input type and then convert that to a natural number since natural numbers are a subset of real numbers ... at least that would be the easiest way to get around the errors incurred by a user inputting doubles or any other floating point type.

Upvotes: 0

Related Questions