Nikunj Banka
Nikunj Banka

Reputation: 11365

Taking EOF as input in C .

I want to print the value of EOF in C .

char ch =getchar() ; 
printf("%d",ch) ; 

this correctly prints the value -1 when I type in CTRL + Z (I am working in windows).

While.

char ch ;
scanf("%c",&ch) ;
printf("%d",ch) ;

incorrectly prints 126 .

What is the reason for this unusual behaviour ?

Upvotes: 1

Views: 181

Answers (4)

ams
ams

Reputation: 25579

You haven't checked the return value from scanf. I'll bet it was zero: no patterns matched.

The value "126" is the uninitialized value of ch.


Edit: on closer inspection of the man page the return value should be EOF. Note that that's the return value, not the value written to ch.

Upvotes: 2

pbhd
pbhd

Reputation: 4467

You should check the return code of scanf, it should return EOF. In this case your char is not affected, and because uninitialized might be 126

Upvotes: 1

Jerry Coffin
Jerry Coffin

Reputation: 490128

EOF is intended to be distinguishable from any value that could be contained in the file being read.

As such, when you're reading from a file, and might receive an EOF, you should not use a char to hold that value. You should use an int, and only convert the result to char after you've verified that what you received was not an EOF. To get correct results, try something like this:

int char;
ch = getchar();
printf("%d", ch);

For your second example, when you read data with scanf, you find out how much (if any) data is read by checking its return value. If it encountered the end of a file, it will simply stop trying to convert input, and you'll find out how many fields were successfully converted by checking its return value. It won't try to convert EOF into a variable.

Upvotes: 1

Zan Lynx
Zan Lynx

Reputation: 54325

What gave you the idea that scanf would fill in a character argument with EOF?

The scanf function hit EOF and it fails to do the conversion and it returns. The value of ch is whatever random value was on the stack when you declared the variable.

Upvotes: 1

Related Questions