所以我必须使用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读取的最大单词。
感谢您的帮助:
答案 0 :(得分: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
答案 1 :(得分:-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++;
}