繁体   English   中英

Fscanf和字符串

[英]Fscanf and Strings

因此,我必须使用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从文本文件中扫描段落,然后为每个单词分配足够的空间并将其放在最后(foo对于扫描位是临时的,它必须是这样)我们知道通过MAXIUM读取的最大字数。

感谢你的帮助:

更改

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 

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

 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++;
 }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM