0

所以我必须使用 fscanf 来扫描文本文件中的一段(单词),并编写了以下代码,理论上它应该可以工作,但我真的不希望有任何帮助。

代码片段:

 char foo[81];
 char *final[MAXIUM]; //this is another way of making a 2d array right?
 int counter=0; 

 while (counter<MAXIUM && fscanf(file, "%s", foo)!= EOF){ 
   *final = (char*)malloc(strlen(foo)*sizeof(foo)); 
   //if (final ==NULL) 
   *(final + counter ) = foo + counter;

   counter++;
 }

文本文件看起来像任何旧段落:

然而,该公司尚未回应客户的社交媒体查询。您可能是狂热的社交媒体爱好者或它的粉丝。


这段代码的要点是仅使用 %s 和 fscanf 从文本文件中扫描段落,然后为每个单词分配足够的空间并将其放入 final (foo 仅用于扫描位,​​它必须是这样做)我们知道通过 MAXIUM 读取的最大字数。

感谢你的帮助:

4

2 回答 2

1

改变

while (counter<MAXIUM && fscanf(foo, "%s", foo)!= EOF){
  *final = (char*)malloc(strlen(foo)*sizeof(foo)); 
  *(final + counter ) = foo + counter;
....
 for(counter=0; i<MAXIMUM; counter++) printf("%s",final[counter])

// Also recommend that the first thing you do is fill your `final[]` with NULL, 0
for (int j=0; j<MAXIUM; j++) final[j] = 0;

// changed fscanf to fgets.  Less issues with dropping whitespace.
while ((counter<MAXIUM) && (fgets(foo, sizeof(foo), stdin)!= EOF)){ 
  final[counter] = (char*)malloc(strlen(foo)+1);  // some say (char*) cast is undesirable, bit allowed.
  strcpy(final[counter], foo);
  // eliminate *(final + counter ) = foo + counter;  
...
for(i=0; i<counter; i++) printf("%s",final[i]);  // The fgets() will preserve the EOL 
于 2013-06-04T02:28:02.253 回答
-1

我认为您应该更改代码,以纠正输出质量

 while (counter<MAXIUM && fscanf(foo, "%s", foo)!= EOF){ 

   /* the  strlen(foo) + 1 for store '\0' */
   final + counter = (char*)malloc((strlen(foo) + 1)*sizeof(foo)); 
   /* to copy the "foo" content  to final + n */
   strcpy(final + counter, foo, strlen(foo));
   /* each time should clear the foo array */
   memset(foo, 0, 81);

   counter++;
 }
于 2013-06-04T02:26:56.450 回答