954,498 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

putchar getchar not workin

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");
zetologos
Newbie Poster
15 posts since Jan 2011
Reputation Points: 10
Solved Threads: 0
 

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?

gerard4143
Nearly a Posting Maven
2,272 posts since Jan 2008
Reputation Points: 512
Solved Threads: 387
 
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.

vinayakgarg
Junior Poster in Training
83 posts since Jan 2010
Reputation Points: 19
Solved Threads: 17
 
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.

Narue
Bad Cop
Administrator
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
 

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

Narue
Bad Cop
Administrator
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You