逐行读取单词并将它们放在数组中 [英] Reading words in line and putting them in array
问题描述
我需要我的程序读取文件的一行,然后解析该行并将任何单词插入到每个数组的索引中.唯一的问题是我不知道每行有多少个单词,每行可以是1-6个单词.
I need my program to read a line of a file, and then parse the line and insert any words into an index of each array. The only problem is that I don't know how many words there are per line, it can be 1-6 words per line.
这就是一个简单文件的样子:
So this is what a simple file can look like:
苹果橙
电脑终端键盘鼠标
如果我扫描第 1 行,我需要一个字符数组来保存单词 apple 和 oranges.示例:
I would need a char array to hold the words apple and oranges if I am scanning line 1. Example:
words[0][0] = "apple";
words[1][0] = "oranges";
到目前为止,我有这样的东西,但我怎样才能使它在每行少于 6 个单词的情况下起作用?
So far, I have something like this, but how can I make it so it works with fewer than 6 words per line?
fscanf(file, "%19[^ ] %19[^ ] %19[^ ] %19[^ ] %19[^ ] %19[^ ]", string1, string2, string3, string4, string5, string6);
推荐答案
您正在阅读整个文件,而不是一行.
You are reading the entire file, not a line.
你可以这样做:
char line [128];
char *pch;
char words[6][20]; // 6 words, 20 characters
int x;
while ( fgets ( line, sizeof line, file ) != NULL ) /* read a line */
{
pch = strtok (line," ,.-");
while (pch != NULL)
{
strcpy(words[x], pch);
pch = strtok (NULL, " ,.-");
}
x++;
/*
At this point, the array "words" has all the words in the line
*/
}
这篇关于逐行读取单词并将它们放在数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!