【发布时间】:2016-06-15 20:16:07
【问题描述】:
所以我将字符打印到文件中,每当行结束时,它都会做一些奇怪的事情。
这是我使用的代码:
void opdracht43() {
FILE *file;
FILE *file2;
file = fopen("opdracht1.1.cpp", "r");
file2 = fopen("Disc.c", "w");
int p;
char a[100];
while (fgets(a, 100, file)) {
for (int i = 0; i < sizeof a; i++) {
if (a[i] == '\n' || a[i] == ' ' || a[i] == '\t') {
printf("TRUE");
}
else {
printf("FALSE");
fputc(a[i], file2);
}
}
return 0; //So it only prints the 1st line for now.
}
fclose(file);
fclose(file2);
}
当它运行时,这是它给出的文本:
#include<stdio.h> ÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌ
> 和 Ì 之间的空格在记事本++中给了我一个奇怪的黑色 nul
文件的第一行是:
#include<stdio.h>
我希望我能在这里找到一些帮助:)
【问题讨论】:
-
您总是试图输出 100 个字节(跳过空格)。但是你应该在输入中遇到
\0时跳出for 循环,因为这标志着fgets读取内容的结束。否则,您将输出过去的有效输入,因此会产生垃圾结果。 -
扩展@kaylum评论,
i < sizeof a应该是i < sizeof(a) && a[i] -
for (int i = 0; i < sizeof a; i++) {-->for (size_t i = 0; a[i]; i++) { -
"奇怪的黑色 nul" 就像
'\0'字符
标签: c file io char file-writing