gpt4 book ai didi

c - 我的代码没有正确地将一个单词替换为另一个单词

转载 作者:行者123 更新时间:2023-11-30 16:22:48 26 4
gpt4 key购买 nike

我刚刚用 c 编写了一个简单的代码,该代码应该从文件中提取文本并将一个单词替换为另一个单词。但是,我不知道为什么,但我的代码只是替换从第二个字母开始的单词。我究竟做错了什么?这是我的代码:

 #include <stdio.h>
#include <stdlib.h>

int main()
{



FILE *f;

char sir[20];

if ((f=fopen("fis.txt","r"))==NULL)
{
printf("Not ok");
exit(1);
}
gets(sir);
fscanf(f, "%s",sir);

printf("Give the word you are looking for and the word to replace it with");
getchar();

char s1[10],s2[10];
gets(s1);
gets(s2);


char *p, aux[100];
while (p=strstr(sir,s1))

{
strcpy(aux,p+strlen(s1));
strcpy(p,s2);
strcpy(p+strlen(s2),aux);
puts(sir);


}


}

最佳答案

我发现你的方法有点太复杂了,只需移动指针就可以简单得多。这是一个粗略的(1)草图:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void)
{
/* Input file */
FILE *f;
/* Buffer for content of input-file */
char sir[100] = { 0 };
/* Temporary memory to hold the result */
/* char tmp[100] = {0}; */
/* Memory for the word to find and the one to replace */
char s1[10], s2[10];
/* Pointer to the occurrence of the word to replace */
char *p;
/* Pointer to sir, the memory holding the content of the file */
char *c;

if ((f = fopen("fis.txt", "r")) == NULL) {
printf("Not ok");
exit(EXIT_FAILURE);
}
/* Read content of file, leave room for the final `\0` */
/* TODO: check return of fread() */
fread(sir, 99, 1, f);

printf("Give the word you are looking for and the word to replace it with: \n");
/* TODO: check return of scanf() */
/* HINT: you should read the two words separately. Ask for the word to find first,
* read it and repeat that for the word to replace. */
scanf("%9s %9s", s1, s2);
/* Give user a change to stay in control. */
printf("You are looking for %s and want it to be replaced with %s\n", s1, s2);

/* We want to move through the input, we can do it quite comfortably with a pointer */
c = sir;
/* For every occurrence of the word to replace */
while ((p = strstr(c, s1)) != NULL) {
/* Print all characters up to the pointer p */
/* TODO: change it to fill tmp instead. */
/* HINT: I would use a pointer to tmp to do it but check the length! */
while (c < p) {
printf("%c", *c);
c++;
}
/* Print the replacement / fill tmp */
printf("%s", s2);
/* Move the pointer to sir to the point in sir after the original word */
c = p + strlen(s1);
}
/* Print / fill tmp with the rest of sir. Check the length if you use tmp! */
printf("%s", c);
/* Get outta here! */
exit(EXIT_SUCCESS);
}

关于c - 我的代码没有正确地将一个单词替换为另一个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54281647/

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