[英]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.