1. easy logic question

Hi,

I'm a freshman EE/CS major in college, and just learned the basics of python in my 1000 level programming course this semester.

I've been trying to begin to learn C, as I'll be needing it for my EE embedded control classes in the future, and have been going through the first couple tutorials on this site, which have been very helpful.

I've run into an issue though regarding 'not equal to' in while/if statements.

I have the following program:

Code:
/*asks for input. If the input is equal to 5, end.*/
#include <stdio.h>

int main()
{
int x;
x = 6;

while (x != 5){
x = getchar();
}
}
If I run it in the command shell, and I enter 5, the program continues and asks for another input.

If I use a for loop, '!=' works. If I use it in an if statement, it does not work.

Anybody see the issue? Can I not use '!=' in the parameters of my while loops/if statements in C?

I'm sure the answer is staring me in the face. If you've taken the time to look at my program and try to find the issue, thank you. 2. Type in a 5 as a response, and getchar() returns the character '5' (ASCII 53 decimal) and you are testing x against the integer 5 in the while statement! 5 != 53! 3. Originally Posted by millsj2 Code:
[…]
while (x != 5){
x = getchar();
}
[…]
The problem is 'x != 5', because you read new values with 'getchar' on 'x', 'x' will have the ascii-value of the character you entered.
If you mean the key '5', then use:
Code:
[…]
while (x != '5'){
x = getchar();
}
[…]
If the value stay alone, then you mean the decimal value.
If the value stay in single quotes, then you mean the character, exactly the internal value (mostly ascii-value) that was used for the character '5'.

EDIT:

The main function returns a integer value, so you should put a 'return 0;' befor the last bracket. 4. having 5 in quotes did the trick!

Thanks for the answers, I did not know you needed quotes if you mean the key value.

That also explains why when I type

printf("%i", '5')

C returns 53. I was confused about that.

Thanks again,
Jesse 5. Python allows you to make that distinction too. While there's no char type like there is in C, python has the functions chr() and ord():
Code:
# Python
s = 'a'
first = s
assert firstChar == s # In python a "char" is just a string
assert ord(firstChar) == 97
assert chr(97) == firstChar
Code:
/* C */
/* In C, strings end with an invisible null character.
Hence the size 2 rather than 1 */
const char s = "a";

/* The first element of s is a char, which is not a string.
'a', not "a" */
char firstChar = s;

/* This comparison wouldn't mean what you think. */
/* assert(firstChar == s); */

/* 'a' and 97 mean the same thing in ASCII */
assert(firstChar == 97);
assert(firstChar == 'a'); Popular pages Recent additions does not equal, easy, logic, question 