c - 如何在文件中写入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)
解决方案
您将宽度声明为一个字符,然后给它一个整数值 (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);
}}
推荐阅读
- python - 如何在 Windows 10 上使用 Python(无需下载)从 Youtube URL 流式传输音频?
- c# - 将数据从 Access 插入 csv 文件的有效方法
- firebase - Firebase 和 Node,js:从用户的 Gmail 发送电子邮件?
- r - 在 usmap 包中使用 plot_usmap() 函数时遇到问题
- tomcat - 在 tomcat 服务器上设置 nonce
- laravel - 为什么在 Laravel 6 中调度作业时作业表为空?
- php - 将一维键值数组转换为二维 kay 值数组,每第 n 个键具有新的键名
- google-apps-script - ARRAYFORMULA 和 COUNTA 仅计数到当前行
- ruby - 按索引将 ruby 数组合并到哈希中
- java - JAVA 8:如何使用 2 STREAM 合并两个列表