0

I have the following bit of code that I'm using to check whether an input is a multiple of 3, 5 or Both. If the user does not enter a number I would like it to print the value stored in UserInput. At the moment it is just returning 0, any suggestions would be much appreciated!

#include <iostream>

using namespace std;

int main()
{
    int UserInput;

    cout << "Please enter a number:";
    cin >> UserInput;

    if (!cin) {
        cout << UserInput;
    }

    else if ((UserInput%3 == 0) && (UserInput%5 == 0)) {
             cout << "FizzBuzz";
    }

    else if (UserInput%3 == 0) {
             cout << "Fizz";
    }

    else if (UserInput%5 == 0) {
             cout << "Buzz";
    }

}
theduck
  • 2,526
  • 13
  • 15
  • 22
  • What did you enter? – BessieTheCookie Nov 29 '19 at 21:35
  • Have a look at this to check whether ```cin``` is a number or not : https://stackoverflow.com/questions/4654636/how-to-determine-if-a-string-is-a-number-with-c – cocool97 Nov 29 '19 at 21:38
  • *If the user does not enter a number I would like it to print the value stored in `UserInput`.* In that case, `UserInput` will be set to zero if you use C++11 or later. Do you really want to print that or do you want to print what the user entered? – R Sahu Nov 29 '19 at 21:40
  • I am completely new to C++ so still learning the basics, @RSahu I want it to print what the user enters. – John Smith Nov 29 '19 at 23:36

1 Answers1

1

If the user input cannot be read into an int, cin is placed in a fail state and nothing is read. The contents of UserInput are useless to you. You will have to take cin out of the error state with clear and read the stream into something guaranteed to be able to hold the user's input like a std::string.

if (std::cin >> UserInput) // Get input and make sure input was read check for good input
{
    // do the fizbuzz thing.
}
else
{
    std::cin.clear(); // remove the error flags set by reading a non-number
    std::string badinput;
    getline(std::cin, badinput); // read the bad input.
    std::cout << "User input: " << badinput << std::endl; // write the bad input 
}
user4581301
  • 29,019
  • 5
  • 26
  • 45