SmiLe ...
SmiLe ...

Reputation: 53

do while and switch error

The error is when I run the program and type n to end choosing it doesn't end and keeps repeating the first cout and the default value:

#include <iostream>
using namespace std;

int main()
{
    int x;
    float y,result=0,paid,change;
    do {
        cout<<"enter another choose or press (n/N) to end choosing ";
        cin>>x;
        switch (x)
        {
        case 1:
            {
                int a=5;    
                cout<<"enter the wighte you want in (Kg) : ";
                cin>>y;
                result=a*y;
                break;}
        default:
            cout<<"wrong choooose "<<endl;
        }

    }
    while (x='n');
    cout<<"your total= "<<result<<endl;
    cout<<"mony value paid = ";
    cin>>paid;
    change =paid-result;
    cout<<"the change = "<<change<<endl;
    return 0;
}

Upvotes: 0

Views: 215

Answers (2)

Ed Swangren
Ed Swangren

Reputation: 124732

Sorry, I totally missed that you're using C++ I/O here.

You declare x as an int, yet you enter the character literal 'n'. The conversion will fail with C++ I/O streams, so x is never set. Don't confuse your data types; if you want to read a char then read a char, same for int.

Try something like this instead:

int x = 0;
do {
    if(!(cin >> x)) {
        cout << "enter a valid number" << endl;
        // clear fail flag
        cin.clear();      
        // consume newline
        cin.ignore(std::numeric_limits<streamsize>::max(), '\n'); 
    } else {
        // your logic here
    }
} while( x != -1 );

while (x='n');

That is not a comparison, it is an assignment, and the character 'n' when converted to an integer will always evaluate to true, so your loop never ends.

Your next problem will be that you want to exit the loop when the input is 'n', not the other way around, so it should be...

while(x != 'n');

Also realize that, if the user enters 110, the loop will exit. x is an int, and the integral value of the character literal 'n' is 110. It will also fail for 'N'.

Upvotes: 2

Some programmer dude
Some programmer dude

Reputation: 409364

The problem is that x is an integer, which you then compare to a character literal.

This works well when using old C-style standard I/O, which uses int instead of char, but doesn't work in C++ where the types are distinct. This means that the input on the line

cin>>x;

will fail if you do not enter a valid integer.

Change the type of x to char and it should work.

There is also the problem with the assignment instead of the condition inside while.

Upvotes: 2

Related Questions