Taylor Patton
Taylor Patton

Reputation: 687

Strange output using if/else in C++

So I have the following code:

char command;
cin >> command;
if ( command == 'P' ) {
    do_something();
}
if ( command == 'Q' ) {
    cout << "Exit\n";
    exit(0);
}
else {
    cout << "command= " command << endl; //use for debugging
    cout << "Non-valid input\n";
    exit(1);
}
cout << "exit at completion\n";
exit(0);
}

When I use input of P, my output after do_something() finishes is:

"output from do_something() function"
command= P
Non-valid input

My question is why do I still get the Non-valid input after do_something() is called in the first if statement? AKA why does the else still run when do_something() finishes?

Upvotes: 2

Views: 426

Answers (3)

taufique
taufique

Reputation: 2751

Your else is associated with second if not the first one. So after finishing first if it enters the else part of second if. Thats why you are getting this. You should use this

char command;
cin >> command;
if ( command == 'P' ) {
    do_something();
}
else if ( command == 'Q' ) {
    cout << "Exit\n";
    exit(0);
}
else {
    cout << "command= " command << endl; //use for debugging
    cout << "Non-valid input\n";
    exit(1);
}
cout << "exit at completion\n";
exit(0);
}

Upvotes: 1

Coding Mash
Coding Mash

Reputation: 3346

The two if statements are independent of each other... The else is with the second if condition. So it never goes into the second if condition and always into its else part. The first if condition has no else part.

Upvotes: 0

Seth Carnegie
Seth Carnegie

Reputation: 75130

You left out the else before the second if, which means that if command != 'Q' (which is true for P), the exit block will be executed.

You probably meant to do

if ( command == 'P' ) {
    do_something();
}
else if ( command == 'Q' ) { // Note the 'else'
    cout << "Exit\n";
    exit(0);
}
else {
    cout << "command= " command << endl; //use for debugging
    cout << "Non-valid input\n";
    exit(1);
}

That way, when the command is P, do_something will be called and all the rest will be skipped.

Upvotes: 5

Related Questions