5

Hi I am now learning the C language and I have a little problem with a exercise of the book I read. My code is this:

#include<stdio.h>
int main()
{
  unsigned char one=0;
  unsigned char two=0;
  printf("Quantity 1 = ");
  scanf("%d",&one);
  printf("Quantity 2 = ");
  scanf("%d",&two);
  printf("The value is %d",one);
  return 0;
}

Why when I am trying to see the value of one the initial value appears and not the value after the scanf?

4

5 回答 5

8

您需要将int类型与%d说明符和说明符char结合%c使用。并%u使用无符号整数。

#include<stdio.h>
int main()
{
    unsigned int one=0; unsigned int two=0;
    printf("Quantity 1 = ");scanf("%u",&one);
    printf("Quantity 2 = ");scanf("%u",&two);
    printf("The value is %u",one);
    return 0;
}

基本上,scanf将尝试从输入中读取整数,并尝试将其存储在不够大的内存位置中,因此您将有未定义的行为。

你可以在这里找到很好的参考。

但是,如果您尝试使用字符作为输入类型,您可能想问自己为什么没有机会输入第二个数量(如果您键入4并按 Enter)。这是因为 secondscanf会将输入键读取为字符。此外,如果您尝试键入21(对于 21 位),它将用第一个值填充2,第二个用1(嗯,用它们的 ASCII 值)填充。

所以,要小心——确保你总是为你的变量选择正确的类型。

于 2013-08-21T19:00:56.060 回答
2

永远不要使用scanf. 永远不要使用scanf. 说真的,永远不要使用scanf.

使用fgets(或者getline,如果你有的话)从用户那里读取一整行输入,然后将字符串转换为带有strtol或它的亲戚strtod和的数字strtoulstrsep也可能有用。

于 2013-08-21T19:09:26.940 回答
1

通过读取其返回值检查是否scanf()正常工作。如需快速入门,请阅读此链接的详细信息scanf()

您正在做的是将整数输入"%d"unsigned char变量中,因此scanf()可能无法正常工作。

于 2013-08-21T19:03:07.190 回答
1

改变

unsigned char one=0; unsigned char two=0;

unsigned int one=0; unsigned int two=0;

并且还使用%u而不是%dthen 它将打印 . 之后的值scanf()

于 2013-08-21T19:03:17.473 回答
1

您将变量声明one为 char:

unsigned char one=0;

但后来你告诉scanf阅读int

scanf("%d",&one);  /* %d means int */

Int 大于 char (通常为 4 字节与 1 字节),导致您描述的问题。

将您更改scanf为:

scanf("%c",&one);  /* %c means char */

然后,当您打印出该值时,还要打印一个字符:

printf("The value is %c",one); /* %c means char */
于 2013-08-21T19:11:52.987 回答