C中的奇数打印行为

时间:2014-04-25 04:16:19

标签: c integer printf

我试图在我的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;
}

3 个答案:

答案 0 :(得分:1)

我看到的问题:

  1. get_field中,您尚未初始化idnum并从该函数返回。

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

    这解释了你得到的输出。

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

    10是'\n'

  3. 的十进制表示
  4. getchar的返回类型为int。您应该将nget_field的类型从int更改为char。根据您正在使用的平台,这可能是问题的根源。

答案 1 :(得分:0)

使用%d打印ASCII值。 ASCII值1为49,\n为10。 这些都是你得到的。

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

答案 2 :(得分:0)

由于nchar类型数据。因此,您必须使用%c代替%d,例如:

    printf("%c this is the response\n",n);
相关问题