【发布时间】:2020-04-16 21:26:29
【问题描述】:
我正在做一个将字母“e”更改为“a”的项目,但我仍然没有完全正确。我的输入是一个文件 abc.txt: '''
Im enne end
my ded is frenk
My mom is elycie Lou
''' 我的输出是“我的妈妈是 alycie Lou”,在另一行中是“我的妈妈是 alicya Lou”。 这是我的代码。谁能帮帮我?
'''
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LINE 3
#define MAX_STRING_SIZE 50
int main()
{
char line[MAX_LINE][MAX_STRING_SIZE];
int i=0;
FILE *arch;
arch = fopen("abc.txt", "r");
if (arch==NULL){
printf("ERROR");
}
else{
while (!feof(arch)){
fgets(line[i], MAX_STRING_SIZE , arch);
i++;
}
}
fclose(arch);
for ( i=0; line[i][MAX_STRING_SIZE]; ++i )
{
if ( line[i][MAX_STRING_SIZE] == 'e' )
{
line[i][MAX_STRING_SIZE] = 'a';
}
}printf("%s", line);
return 0;
}
'''
【问题讨论】:
-
您正在将所有行读取到同一个缓冲区中,最终只得到最后一行(每次读取新行时都会覆盖前一行)。尝试在 while 循环中处理每一行,在阅读后立即处理,而不是在末尾。
-
另外,
for循环没有意义......您正在迭代字符串中的字符以进行替换,但每次替换字符时打印字符串而不是在所有替换完成后只需一次。