首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Fscanf和Strings

Fscanf和Strings
EN

Stack Overflow用户
提问于 2013-06-04 02:10:52
回答 2查看 170关注 0票数 0

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

代码片段:

代码语言:javascript
复制
 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读取的最大单词。

谢谢你的帮助:

EN

回答 2

Stack Overflow用户

发布于 2013-06-04 02:28:02

变化

代码语言:javascript
复制
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])

代码语言:javascript
复制
// 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 
票数 1
EN

Stack Overflow用户

发布于 2013-06-04 02:26:56

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

代码语言:javascript
复制
 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++;
 }
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16908760

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档