Cant get out of my do-while loop

When I press X or x it does not end the program, instead it prompts my default case, then the loop starts all over again.

[code]
#include <iostream>
#include <string>
#include <fstream>
using namespace std;

int main()
{
ofstream testfile1;

int sum = 0;
int teacount = 0;

int coffeecount = 0;

char lastorder = ' ';
int teasum = 0;
int coffeesum = 0;

string name = "";
testfile1.open("testname.txt", ios::app);


do {

cout << "C- coffee ($2) \n ";
cout << "T- TEA ($3) \n ";

cin >> lastorder;

switch (lastorder) {
case 'C': {

coffeecount ++;
cout <<"Coffee "<< "!" << coffeecount << "!" << endl;
break;
}
case 'c': {

coffeecount++;
cout <<"Coffee"<< "!" << coffeecount << "!" << endl;
break;
}
case 'T' : {

teacount++;
cout <<"TEA "<< "!" << teacount << "!" << endl;
break;
}

case 't': {

teacount++;
cout << "TEA " << "!" << teacount << "!" << endl;
break;
}


default: {

cout << " wrong order try again ! \n";
}

}


}while ( lastorder != 'X'|| lastorder != 'x');

coffeesum = coffeecount * 2;
teasum = teacount * 3;
sum = coffeesum + teasum;
testfile1 << sum<<endl;

cout << "Coffe: " << coffeecount << endl;
cout << "Tea: " << teacount << endl;
cout << "Total cost: " << sum << endl;

testfile1.close();


return 0;
}
1
2
3
4
default: {

cout << " wrong order try again ! \n";
}


Should be :
1
2
3
4
case 'x' : case 'X' : break;
default: {
cout << " wrong order try again ! \n";
}
}while ( lastorder != 'X'|| lastorder != 'x');

When lastorder is 'x' then the left side of the condition is true, so the entire condition evaluates to true. Likewise with the right side of the condition. When lastorder is 'X' the right side is true, so the entire condition is true.

You need:

}while ( lastorder != 'X' && lastorder != 'x');

You might want to review truth tables for logical and/or.
Last edited on
Your condition( lastorder != 'X'|| lastorder != 'x') will result in an infinite loop.

This is because of how if lastorder is 'x' it will see that it doesn't equal 'X' resulting in true, and vice versa if lastorder is 'X'. Remember ||(or) is true so long as one of the conditions is true.

Here are two fixes, change ||(or) to &&(and)( lastorder != 'X' && lastorder != 'x'); or have the comparisons be equal with a not statement e.g, ( !(lastorder == 'X' || lastorder == 'x'));

Although you should use the first one since it's easier to read.

Also PLEASE use code tags next time! It helps everyone read and understand the code that you are posting. To add code tags click the <> tag on the format section to the right.
Last edited on
Topic archived. No new replies allowed.