来自文件中单行的字符串数组

Array of strings from single line in a file

我想从 .txt 文件中获取字符串数组。我尝试使用 fgets 然后使用 strtok 来分隔字符串。我认为我的 fgets 是错误的,但我不明白如何得到我想要的。

char* str[numWords];
char line[] = fgets(str, numCharTotal, filep);
char delim[] = " ";
int j;
for(j = 0; j != numWords; j++)
{
       str[j]= strtok(line, delim);
}

换句话说,我有一个 .txt 文件

This is a txt file

我希望能够以

的形式拥有它
char* str[] = {"This","is","a","txt","file"};

printf("%s", str[0])  //then "This" is printed
//...
//Till last word of txt file
//...
printf("%s", str[4])  //then "file" is printed

你应该把声明:

line = fgets(str, numCharTotal, filep);

在循环外,使用循环一次读取'line'一个单词。

目前,循环的第一次迭代读取第一行,然后读取第一个单词。然后其他迭代将尝试读取文件的下一行,这些行是空的

fgets will read a line from your file and store it in a string. You need to allocate memory for you buffer (char array line in your code). After calling strtok with the char array line as the first parameter, loop through calling strtok 第一个参数传入 NULL。如果继续传递char数组行,每次循环只会得到第一个token(单词)

char *str[numWords];
char line[numCharTotal];
char delim[] = " ";
int j = 0;

fgets(line, numCharTotal, filep);

char *token = strtok(line, delim);
while (token != NULL) {
    str[j] = token;
    ++j;
    token = strtok(NULL, delim);
}

for (int i = 0; i < numWords; ++i) {
    printf("%s\n", str[i]);
}