因此,我必须使用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读取的最大单词。
谢谢你的帮助:
发布于 2013-06-04 02:28:02
变化
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-04 02:26:56
我认为您应该修改代码,以纠正输出量。
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++;
}https://stackoverflow.com/questions/16908760
复制相似问题