Monday, May 16, 2011

Function :GetChar()

int getchar ( void );
Get character from stdin

Returns the next character from the standard input (stdin). It is equivalent to getc with stdin as its argument.

Parameters: (none)

Return Value : The character read is returned as an int value.

If the End Of File is reached or a reading error happens, the function returns EOF and the corresponding error or eof indicator is set. You can use either ferror or feof to determine whether an error happened or the End-Of-File was reached.
 
Example:
int character=1;


while (plainChar != EOF) {
character= getchar();
printf("%c\n", character);

Important (may be interview question sometimes)
What's wrong with this code?

char anyCharacter;

while((anyCharacter = getchar()) != EOF) ...
Correct Explaination:
The variable to hold getchar's return value must be an int. EOF is an ``out of band'' return value from getchar: it is distinct from all possible char values which getchar can return. (On modern systems, it does not reflect any actual end-of-file character stored in a file; it is a signal that no more characters are available.) getchar's return value must be stored in a variable larger than char so that it can hold all possible char values, and EOF.


Two failure modes are possible if, as in the fragment above, getchar's return value is assigned to a char.
If type char is signed, and if EOF is defined (as is usual) as -1, the character with the decimal value 255 ('\377' or '\xff' in C) will be sign-extended and will compare equal to EOF, prematurely terminating the input.
If type char is unsigned, an actual EOF value will be truncated (by having its higher-order bits discarded, probably resulting in 255 or 0xff) and will not be recognized as EOF, resulting in effectively infinite input.


Inspired By :
http://c-faq.com/stdio/getcharc.html



return 0;

}

No comments:

Post a Comment

Health Benefits of Cashews

  Benefits of Cashews. Healthy food is an integral part of healthy body. Regular exercises such as Yoga and healthy diet is important to...