2013-10-29 74 views
1

我需要我的程序读取文件的一行,然后解析该行并将任何单词插入每个数组的索引中。唯一的问题是我不知道每行有多少字,它可以是每行1-6个字。在线阅读单词并将它们放入数组

所以这是一个简单的文件可能是什么样子:

苹果橘子

计算机终端键盘鼠标

我需要一个字符数组来保存的话苹果和桔子如果我正在扫描第1行。 例如:

words[0][0] = "apple"; 
words[1][0] = "oranges"; 

到目前为止,我有这样的事情,但我怎样才能使它每行少于6个字?

fscanf(file, "%19[^ ] %19[^ ] %19[^ ] %19[^ ] %19[^ ] %19[^ ]", string1, string2, string3, string4, string5, string6); 
+1

为什么不读整行?并使用空间分隔符分割? – niko

+1

'fgets'和'strtok' – Duck

回答

-1

您正在阅读整个文件,而不是一行。

你可以做这样的事情:

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 
     */ 

     } 
相关问题