-1

I'm currently writing a program to check if a user inputs 0.0 or any variation of 0. However, if I were to write the following code with the user input as 0.0 I don't get either right or wrong as an output the program just ends.

int main(){
    double num;
    cin >> num;
    if (num==0){
        cout << "wrong";
    }
    else {
        cout <<"right";
    }
}

Can someone explain the reason I don't get anything and possibly how to do the comparison I need?

Update: The code I was running is correct, it didn't output because I wasn't calling the function in main. The only reason my post has the code in main was to simplify my question.

3 Answers3

3

It's impossible for the program you have given to output nothing. You must be running different code. You may need to recompile it. Or, you might not be seeing the output for some reason. Try adding \n at the end of the strings you print, in case the next prompt is overwriting it somehow.

Dan
  • 12,409
  • 3
  • 50
  • 87
  • That's exactly what I was thinking but when I ran it both visual studio and cpp.sh gave me the same no output when I originally asked this question. However it works now oddly enough. I wish I screen grabbed it because it blew my mind. – John McNair Nov 06 '16 at 00:25
1

You may need << std::endl or << std::flush at the end of your cout statements.

interputed
  • 93
  • 5
  • "If the main function returns to its original caller, or the exit(3) function is called, all open files are closed (hence all output streams are flushed) before program termination." – Dan Nov 06 '16 at 10:18
0

This program is guarenteed to print out right or wrong, you must be running different code or maybe your ide/settings are somehow disabling output to the console, like a gui application

As a side note, do some research on the ternary operator, and your code could be shortened to:

double num;
cin >> num;
std::cout << (num == 0) ? "wrong":"right" << std::endl;