【问题标题】:Odd printing behavior in CC中的奇怪打印行为
【发布时间】:2014-06-10 15:11:49
【问题描述】:

我试图在我的 C 程序中打印出逗号分隔的值,但我认为我一直在获得内存分配。 从命令行运行时,会发生这种情况。

1
  49 this is the response
  10 this is the response
1
  49 this is the response
  10 this is the response

这是我的程序:

void main(){
    int j;
    int idnum;
    j = 0;
    char entry[99];
    do{
        idnum = get_field(entry);
        j++;
    }
    while(idnum!='\n' && idnum!= ',' && j!= MAXTYPES);
    int recur = 0;
    while (recur != 4){
        printf("%4d\n", entry[recur]);
        recur++;
    }
    printf("\nEnd of Input\n");
}

int get_field(char entry[]){
    int idnum;
    char n;
    int j = 0;
    char temp[45];
    while ((n=getchar())!= EOF){
        printf("%d this is the response\n",n);

    }
    return idnum;
}

【问题讨论】:

  • 也许你想要printf("%c this is the response\n",n);

标签: c integer printf


【解决方案1】:

我看到的问题:

  1. get_field中,你还没有初始化idnum并从函数中返回它。

  2. get_field 中,读取数据的while 循环很奇怪。我不确定您要完成什么。但是,如果您键入1,然后按Enter,则会将两个字符添加到输入流中:'1''\n'。您将它们读取为字符,使用getchar,并将它们打印为int(使用"%d" 格式)。

    这解释了你得到的输出。

    49 是'1' 的十进制表示。

    10 是'\n' 的十进制表示

  3. getchar 的返回类型是int。您应该将get_fieldn 的类型从char 更改为int。这可能是问题的根源,具体取决于您使用的平台。

【讨论】:

    【解决方案2】:

    使用%d,您正在打印 ASCII 值。 ASCII 值 1 是 49,\n 是 10。 这些就是你得到的。

    您可能希望使用%c 打印它们。

    【讨论】:

      【解决方案3】:

      由于nchar 类型的数据。所以,你必须使用%c 而不是%d 像这样:

          printf("%c this is the response\n",n);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-03-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-09-29
        • 2011-10-24
        相关资源
        最近更新 更多