在C语言中将文件中的字指定给数组
我希望程序从输入文件input.txt中读取,识别每个单词,并将每个单词保存为一个名为a的数组中的字符串 我尝试过按照其他建议进行操作,但没有效果。我当前的代码可以打印出数组中的每个单词,但似乎可以将单词保存到数组中的每个项目,而不是仅保存一个 任何帮助都将不胜感激 示例输入文件:在C语言中将文件中的字指定给数组,c,arrays,C,Arrays,我希望程序从输入文件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:
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);
}
#包括
常量char*readInputFile(char inputUrl[]){
字符输入线[200];
字符输入缓冲区[200];
常量字符*A[1000];
int i=0;
FILE*FILE=fopen(inputUrl,“r”);
如果(!文件){
printf(“错误:无法打开输入文件”);
返回NULL;
}
而(!feof(文件)){
fscanf(文件“%[^\n\t\r]”,inputLine);//获取输入文本
A[i]=输入线;
fscanf(文件“%[\n\t\r]”,inputBuffer);//删除所有空白
printf(“%s\n”,A[i]);
i++;
}
printf(“此输出应该是第一个字,而不是最后一个字:%s\n”,A[0]);
fclose(文件);
}
int main(){
readInputFile(“input.txt”);
返回(0);
}
要复制到数组每个元素中的内容实际上是inputLine指向的字符串的地址。循环的每次迭代都会更改指向的字符串,并且所有数组元素都指向同一个字符串
您需要通过分配内存空间来保存该字符串(malloc),然后将其逐字母复制到新位置(strcpy)来创建该字符串的副本
[编辑]您可能还希望在复制字符串之前删除字符串中的空白;)[/编辑]
#包括
#包括
#包括
常量char*readInputFile(char inputUrl[]){
字符输入线[200];
字符输入缓冲区[200];
字符*A[1000];
int i=0;
FILE*FILE=fopen(inputUrl,“r”);
如果(!文件){
printf(“错误:无法打开输入文件”);
返回NULL;
}
而(!feof(文件)){
fscanf(文件“%[^\n\t\r]”,inputLine);//获取输入文本
A[i]=malloc(strlen(inputLine)+1);
strcpy(A[i],输入行);
fscanf(文件“%[\n\t\r]”,inputBuffer);//删除所有空白
printf(“%s\n”,A[i]);
i++;
}
printf(“此输出应该是第一个字,而不是最后一个字:%s\n”,A[0]);
fclose(文件);
}
int main(){
readInputFile(“input.txt”);
返回(0);
}
尝试更改A[i]=inputLine代码>到A[i]=strdup(inputLine)代码>。将inputLine
赋值给A[i]
只会复制指针,而不是字符串。另外,while(!feof(file))
在这里并不重要,但是在处理完这些字符串之后,调用free(a[i])
将是一个好主意。
#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);
}