gpt4 book ai didi

c - 将文件中的单词分配给 C 中的数组

转载 作者:行者123 更新时间:2023-11-30 16:50:15 25 4
gpt4 key购买 nike

我希望程序从输入文件 input.txt 中读取,识别每个单词,并将每个单词作为字符串保存在名为 A 的数组中。

我尝试遵循其他建议但无济于事,我当前的代码可以打印出数组中的每个单词,但似乎将该单词保存到数组中的每个项目,而不是仅保存一个。

任何帮助将不胜感激。

示例输入文件:

Well this is a nice day.

当前输出:

Well
this
is
a
nice
day.
This output should be the first word, not the last: day.

我的代码:

#include <stdio.h>

const char * readInputFile(char inputUrl[]) {
char inputLine[200];
char inputBuffer[200];
const char * A[1000];
int i = 0;

FILE *file = fopen(inputUrl, "r");
if(!file) {
printf("Error: cannot open input file.");
return NULL;
}

while(!feof(file)) {
fscanf(file,"%[^ \n\t\r]",inputLine); // Get input text
A[i] = inputLine;
fscanf(file,"%[ \n\t\r]",inputBuffer); // Remove any white space
printf("%s\n", A[i]);
i++;
}
printf("This output should be the first word, not the last: %s\n", A[0]);
fclose(file);

}

int main() {
readInputFile("input.txt");


return(0);
}

最佳答案

您复制到数组每个元素中的实际上是 inputLine 指向的字符串的地址。循环的每次迭代都会更改指向的字符串,并且所有数组元素都指向同一个字符串。

您需要通过分配内存空间来保存字符串(malloc)来创建字符串的副本,然后将其逐个字母复制到新位置(strcpy)...

[编辑]您可能还想在复制字符串之前删除字符串中的空格;)[/edit]

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

const char * readInputFile(char inputUrl[]) {
char inputLine[200];
char inputBuffer[200];
char * A[1000];
int i = 0;

FILE *file = fopen(inputUrl, "r");
if(!file) {
printf("Error: cannot open input file.");
return NULL;
}

while(!feof(file)) {
fscanf(file,"%[^ \n\t\r]",inputLine); // Get input text
A[i] = malloc(strlen(inputLine)+1);
strcpy(A[i], inputLine);
fscanf(file,"%[ \n\t\r]",inputBuffer); // Remove any white space
printf("%s\n", A[i]);
i++;
}
printf("This output should be the first word, not the last: %s\n", A[0] );
fclose(file);

}

int main() {
readInputFile("input.txt");

return(0);
}

关于c - 将文件中的单词分配给 C 中的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42259010/

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