Enter a char in struct using getche in C?

I have a problem entering char in C. I want the user to enter only x or x . If not, the user must enter again. Moreover, I want to do this with structure. This is my code:

 typedef struct chu{ char c; }; int main(){ chu input; char temp; do{ printf("\nInput: "); temp=getche(); if((temp!='x')||(temp!='X')) printf("\nWrong input (only 'x' or 'X')"); else input.c=temp; }while((temp!='x')||(temp!='X')); } 

When I enter x or x , I do not have to enter again.

+4
source share
2 answers

If you are mistaken, this should be:

 if((temp!='x') && (temp!='X')) ^ && if not both 

I replaced || on && (because either of them is accepted, therefore, if temp is not equal to both, then the condition should print an incorrect message)

Secondly, the condition should be:

 while(!((temp =='x') || (temp=='X'))); ^ 

how do you say. When I entered x or X, I should not enter again. So if temp is either x or x , then (temp =='x') || (temp=='X') (temp =='x') || (temp=='X') == 1 , but because of ! it gives while(0) and loop breaks

In addition, your structure definition should look like this:

 typedef struct { char c; }chu; 

I adjusted your code, you can find from here and try your car.

+3
source

The problem depends on your condition:

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

This means: Repeat until it is equal to "x" OR "X". (This is always true because it can only be one or the other. Replace it as follows:

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

Repeat until it is “x” or “X”. The same problem is in your if further (I seem to have missed this for the first time, my bad one).

Your code can be restored as follows:

 int main(){ chu input; char temp; while(true) { printf("\nInput: "); temp=getche(); if(temp != 'x' && temp != 'X') printf("\nWrong input (only 'x' or 'X')"); else { input.c=temp; break; } } } 

This code will be looped forever (as indicated by while(true) ), but as soon as you enter 'x' or 'X', it will set the variable to your structure and break free from your loop.

Some information about semantics:

Everything related to OR ( || ) ceases to be evaluated as soon as the first condition returns true . At this point, the whole construct will return true , no matter what.

On the contrary, everything that you associate with AND ( && ) stops evaluating as soon as the first condition returns false , since it makes the whole construct false anyway.

To get back to your example, this is what your compiler does, assuming we enter "X"

 if(temp != 'x') { //Okay, it not 'x'. Let try the next one. if(temp != 'X') { //Oh wait, it IS X. I can't stop yet! //Stop looping } //This will be executed } //Loop me! 

And this is what he does with &&

 if(temp == 'x') { //Hmm...not 'x'. if(temp == 'X') { //Oh wait! It IS 'X'. //Stop looping //This gets executed. } } //Loop me! 

You may have noticed that I changed != To == here. I can do this due to binary arithmetic. NOT (x OR X) equals (NOT x AND NOT X).

+1
source

All Articles