首页 > 解决方案 > 如何在文件中写入char变量?

问题描述

void main {
char width;

width = 2;

FILE *file = fopen("file.txt", "w")
if (file != NULL) {      
fputc ('c', file) //writes correctly.
fputc (width, file) //has no effect
fclose(file);
}}

在上面的代码片段中,我试图将我定义的变量“宽度”写入某个文本文件。文件打开,第一个 c 被写入。我还想在文本文件中写入宽度值。我希望它包含 c2 ('c' + width)

标签: cstdout

解决方案


您将宽度声明为一个字符,然后给它一个整数值 (2),您需要将其设为“2”而不是 2。当您将这样的整数值分配给一个字符时,该字符是根据ASCII 表分配的。ASCII 为 2 是不可打印的字符 STX(文本开头)。您可以发现该字符'2'的 ASCII 为 50。

void main {
char width;

width = '2'; // Note my change.
width = 50; // This will work too. (You need only this line or only the above line, they are both equivalent based on the ASCII table)

FILE *file = fopen("file.txt", "w")
if (file != NULL) {      
fputc ('c', file) //writes correctly.
fputc (width, file) //has no effect
fclose(file);
}}

推荐阅读