hello, im newbie here and also newbie in c++. I have a problem with char data type. I try writing the code input character 'D', 'd', 'R' and 'r'. if input are correct, the output will be 'OK' but turn out, even I give input other character, still give the output 'OK'. anyone can help me resolve the problem?

this is my code;

#include <iostream>
using namespace std;

int main () {
    char choice ; 
    choice = 'D', 'R', 'd', 'r';

    cout << "Insert choice: ";
    cin >> choice;

    if ( choice == 'D' || 'd' || 'R' || 'r' ) {
        cout << "OK!" << endl;

    }   
    else
        cout << "Nub!" << endl;

       return 0;

}

p/s: im using mingw g++ compiler

Recommended Answers

All 5 Replies

cant help u with this. I'm still at c program. sorry bro

cant help u with this. I'm still at c program. sorry bro

Then why bother posting?

@OP, you have more than 1 issues with your code. But I'll let someone handle out the details. But to answer your question, you if statement should be :

//read as : "if choice is equal to 'D' or if choice is equal to 'd' or if ...
if ( choice == 'D' || choice == 'd' || choice ==  'R' || choice == 'r' ) {
       /* Success */
}	
else { /* face palm */ };


@OP, you have more than 1 issues with your code. But I'll let someone handle out the details. But to answer your question, you if statement should be :

//read as : "if choice is equal to 'D' or if choice is equal to 'd' or if ...
if ( choice == 'D' || choice == 'd' || choice ==  'R' || choice == 'r' ) {
       /* Success */
}	
else { /* face palm */ };

owh, thanx very much! ^^,

any idea how to create a loop if user input wrong characters..?? i tried to do while loop but it never works.. anyone..??

double input_x, number;
cout << "Insert value: ";
cin >> input_x;


char choice ; 
choice = 'D', 'R', 'd', 'r';

cout << "Insert choice: ";
cin >> choice;

while ( //what suppose i write here?? )

if ( choice == 'D' || choice == 'd' ) {
    number = input_x * 3.142 / 180;



}   
else if ( choice == 'R' || choice == 'r') {
    number = input_x;

    }
else {
    cout << "Invalid input!" ;
    }

}
    cout << "The number in radian is: " << number << endl;
bool invalidInput = true;
while(invalidInput) {
    cout << "Enter choice: ";
    cin >> choice;
    switch((int)choice) {
        case 'D':
        case 'd':
            cout << "Do things for D\n";
            invalidInput = false;
            break;
        case 'R':
        case 'r':
            cout << "Do things for R\n";
            invalidInput = false;
            break;
        default:
            cout << "Invalid input\n";
    }
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.