将结构中的int转换为C中的字符串

时间:2017-05-05 04:03:19

标签: c

我正在尝试将struct中的int值转换为字符串,以便我可以将它们写入ppm文件的标头。

结构定义如下:

typedef struct {
    int width;
    int height;
    int maxColourVal;
    FILE *ppmFilePointer;
} PpmStruct;

创建新ppm文件的功能:

PpmStruct *newWritePpm(const char *filename, PpmStruct *parentPpm){
    FILE *outfile = fopen(filename, "w");
    if (!outfile){
        printf("Unable to open '%s'\n", filename);
        exit(1);
    }
    PpmStruct *newPpm;
    newPpm = (PpmStruct *)malloc(sizeof(PpmStruct));

    /* Populating ppm struct*/
    (*newPpm).width = (*parentPpm).width;
    (*newPpm).height = (*parentPpm).height;
    (*newPpm).maxColourVal = (*parentPpm).maxColourVal;
    (*newPpm).ppmFilePointer = outfile;

    /* writing outfile ppm header to file*/
    fputs("P6\n", outfile);
    fputs((*parentPpm).width, outfile);
    fputs(" ", outfile);
    fputs((*newPpm).height, outfile);
    fputs("\n", outfile);
    fputs((*newPpm).maxColourVal, outfile);
    fputs("\n", outfile);
    /* leaves pointer at start of binary pixel data section */

    return(newPpm);
}

在编译时,我从编译器得到几个类似的警告:

ppmCommon.h: In function ‘newWritePpm’:
ppmCommon.h:75:8: warning: passing argument 1 of ‘fputs’ makes pointer from integer without a cast [-Wint-conversion]
  fputs((*parentPpm).width, outfile);

1 个答案:

答案 0 :(得分:2)

fputs用于编写字符串。 parentPpm->width 是一个整数。对于Netppm formats,您需要输出ASCII十进制整数。最简单的方法是对整个标题使用一个fprintf调用:

fprintf(outfile, "P6\n%d %d\n%d\n", 
        parentPpm->width, newPpm->height, newPpm->maxColourVal);