this code doesnt work, as in it only asks the user for getchar once and putchar once. i tried putting it in two method and it didnt work either. also whether it be char or int it is the same. that leads me to another question. why is it allowed to store chars in ints. also if i put getchar in a while loop and make the condition t = eof, how does it know its the end of me typin something.

char t = getchar();
putchar(t);
printf("\n");

int x = getchar();
putchar(x);
printf("\n");

When you enter a character from the console you hit return as well so you really enter two characters..e.g

Enter the character 'a' plus return yeilds

'a', '\n'

Instead of using putchar() try using

fprintf(stdout, "value->%d\n", t);
fprintf(stdout, "value->%d\n", x);

What values were displayed?

why is it allowed to store chars in ints

because int (2 or 4 bytes)is bigger than char (1 byte), there is no data loss in assigning char to int, while the converse may lead to data loss.

why is it allowed to store chars in ints.

char is an integer type, just with a smaller range than int . It makes sense that since int can hold every value char can, a widening conversion from char to int should be possible.

also if i put getchar in a while loop and make the condition t = eof, how does it know its the end of me typin something.

You signal end-of-file from the command line (Ctrl+C on Windows, Ctrl+D on Unix//Linux), getchar will recognize it, and return the EOF macro. Note that EOF is an integer, which is why you should use an int to store results from getchar.

Correction, Ctrl+Z instead of Ctrl+C for Windows. Thanks to jonsca for catching the brain fart. ;)

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.