开发者

Difference between reading a variable using scanf and assignment

int main()
{
  int i,j;
  i='c';

  scanf("%d",&j);   // I will read 'c' here 

  printf("%d %d",i,j);

}

Output 开发者_如何学Gois not same.'j' takes garbage value and 'i' takes ascii value of 'c'. Can anybody tell what could be the reason ?


You scanf says:

scanf("%d", &j);

With this sentence scanf will try to parse (convert) the 'c' character you are using as input to the function into a number. That's way you get garbage. C doesn't know how to turn 'c' into a number, because scanf is expecting digits.

Try changing that to:

scanf("%c", &j);

If your printf call is like this:

printf("%d %d", i, j);

You should get the same value, both times: ASCII value of 'c' character.


You have two issues here.

First of all, you're calling scanf with %d. This means scanf will look for a decimal character and put it in j. It won't find any, so it will leave j unchanged.

The first thing you need to do is change %d to %c.

Now you have another problem. j is an int, but you're reading a char into it. A char is commonly smaller than an int. Usually a char is 8 bits, while an int is 32 or 64 bits. What will happen now is that scanf will put the ascii value of 'c' into the lower byte of j, but leave the rest unchanged.

You need to either clear out j explicitly:

int j = 0;

or declare it as a char:

char j;

This shows the difference between assigning the int or using scanf. The scanf function doesn't know that j is an int. It guesses what pointers were sent to it based on the format string. When you use the %c format, you're telling scanf to treat &j as a pointer to a char, while if you explicitly assign it with

j = 'c'

The compiler knows that 'c' is a char and j is an int, and will do the correct conversion for you, including zeroing out the upper bits.


You are not reading really anything into j. My guess is j will be zero-initialized by your compiler and output 0. Since we really don't know, in your case, what j actually did print out - we can only assume that is the case. In your other example, i, it will likely print the ascii value of 'c' which is 99. If you want to read a character into j, then you also need to change the %d to a %c. But my guess is you really did not intend to use j and it would be replaced with i so you can compare the differences.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜