Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

Help with cin >> and cin.fail()?

rwhite10rwhite10 UKMember Posts: 1

I am new to C++ but not to programming in general. I was making a very basic program that players around with user inputs and integers to find out about syntax and how C++ works etc. This code:

#include <iostream>
#include <stdlib.h>
using namespace std;

int main()
{
    int a,b,c;          //Assigns 'a', 'b', and 'c' as an integer
    int result;         //Assigns 'result' as an integer 

    cout << "\n";
    cout << "This prints out ('a'*'b') then the remainder when divided by 'c' \n";  //Simple string to show what program does

    //Start processing for 'a'
    cout << "Please enter an integer value for 'a' \n";
    cin >> a;
    if (cin.fail()) {
        cout << "Bad input. Program terminating! \n";
        abort();
        }
    //End of processing for 'a'

    //Start 'b' processing
    cout << "Please enter an integer value for 'b' \n";
    cin >> b;
    if (cin.fail()) {
        cout << "Bad input. Program terminating. \n";
        abort();
        }
    //End of Processing for 'b'

    //Start Processing for 'c'      
    cout << "Please enter an integer value for 'c' \n";
    cin >> c;
    if (cin.fail()) {
        cout << "Bad input. Program terminating! \n";
        abort();
        }
    //End of Processing for C

    result = (a * b) % c;       //Gives result a value

    cout << "\n";
    cout << "Your final result is " << result; //prints result
    cout << "\n";

    return 0; //terminate program
}

Runs perfectly fine when integers are used as the user input when prompted. Along with this, entering a letter/punctuation mark provides this output:

This prints out ('a'*'b') then the remainder when divided by 'c'
Please enter an integer value for 'a' 
!
Bad input. Program terminating! 
Aborted (core dumped)

(Sorry for labelling that as code, this is the output I get in the terminal)

Which is also correct. However, using a number with a decimal point (float) provides this:

This prints out ('a'*'b') then the remainder when divided by 'c' Please enter an integer value for 'a' 4.5 Please enter an integer value for 'b' Bad input. Program terminating. Aborted (core dumped)
(Again, this is a terminal output)

As you can see, when I use a float over an integer, before the program terminates, it prompts the user for a value for 'b'. However this is not the case for using a letter/punctuation mark. Can someone please explain this as well as how/if I can resolve this. Thanks all :)

Tagged:
Sign In or Register to comment.