2

This code is not working correctly, please help me. Even though I entered the right character it keeps asking "enter right number". And it does not evaluate the condition.

#include<iostream>
#include<conio.h>
#include<string>
using namespace std;
int main()
{
    char ch = '0';
    A:
    cout << "enter a Character" << endl;
    cin >> ch;
    if ((ch != 'X')||(ch != 'x'))
    {
        cout << "Please Enter Right Number" << endl;
        goto A;
    }
    return 0;
}
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
SAIFI369
  • 87
  • 1
  • 2
  • 11

2 Answers2

3

use

    if ((ch != 'X') && (ch != 'x'))

instead of

  if ((ch != 'X')||(ch != 'x'))

Also instead of using goto you could use a loop

 cout << "enter a Character" << endl;
 cin >> ch;
 while(ch!='X' && ch!='x')
 {
      cout << "Please Enter Right Number" << endl;
      cout << "enter a Character" << endl;
      cin>>ch;
 }
Gaurav Sehgal
  • 7,422
  • 2
  • 18
  • 34
  • 1
    First of all Thanks to all of you. Second sorry I have tried many times but I didn't found the related answer thats why i asked New Question. Just after posting my Q, in a blog I read that != doesn't works with the chat type instead it works with string I have tried this and its working but Is this true that it doesn't works with the char type. – SAIFI369 Jul 04 '15 at 19:25
  • `!=` very well works with `chars`.Didn't your code work after correction? – Gaurav Sehgal Jul 04 '15 at 19:30
  • Please explain your answer that why I have to use && instead of ||. Thanks – SAIFI369 Jul 04 '15 at 19:33
  • @SAIFI369.The program should stop when user enters `X` or `x`.So the program should continue asking for another character if user entered something other than `X` or `x` ie continue if character entered is neither `X` nor `x`.Tell me if that made sense. – Gaurav Sehgal Jul 04 '15 at 19:38
  • OK What I want to do is that if the character entered is other than X or x then program should ask the user to enter it again. That's it. – SAIFI369 Jul 04 '15 at 19:47
  • Yes my code works after I made changes that you mentioned. – SAIFI369 Jul 04 '15 at 19:54
2

(ch != 'X')||(ch != 'x') is always true, you probably means && instead of ||.

Jarod42
  • 203,559
  • 14
  • 181
  • 302
  • 1
    correct, but duplicate duplicate duplicate duplicate - how many hundreds of these do we have to answer? – rghome Jul 04 '15 at 10:46