gpt4 book ai didi

c - 将字符打印到文件会产生奇怪的结果

转载 作者:行者123 更新时间:2023-11-30 18:12:27 25 4
gpt4 key购买 nike

所以我将字符打印到文件中,每当行结束时它就会做一些奇怪的事情。

这是我使用的代码:

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> ÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌ

> 和 Ì 之间的空格在 Notepad++ 中给了我一个奇怪的黑色 nul

文件的第一行是:

#include<stdio.h>

我希望我能在这里找到一些帮助:)

最佳答案

改变

for (int i = 0; i < sizeof a; i++) {

for (int i = 0; a[i] != '\0' && i < sizeof a; i++) {

就您而言,在第一次调用 fgets() 时给出数组 a这些值:“#”、“i”、“n”、“c”、...、“o”、“.”、“h”、“>”和“\0”。然而,其余的a仍然包含像 Ì 这样的垃圾,因为a从未初始化。

'\0'就是你提到的“奇怪的黑色nul”。 '\0' 是 C 风格字符串结束的信号,但它并不代表文件的结束,因此不应使用 fputc() 将其写入“Disc.c”。

关于c - 将字符打印到文件会产生奇怪的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35756345/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com