![](/img/trans.png)
[英]Reading multiple strings from file seperated with space, using fscanf
[英]Reading strings, integers etc from files using fscanf
我希望您能幫助我理解如何執行以下操作:
我有一個包含由空格''分隔的整數的文件。 我需要讀取所有整數,對它們進行排序並將它們作為字符串寫入另一個文件。 我寫了一個代碼,但是我通過char讀取char,把這個單詞放在char sub_arr [Max_Int]中,當我遇到''時,我將這些字符放入另一個Main int數組后,現在放入一個字符串,直到到達文件的末尾,逐個字符串,然后我對它們進行排序並將它們寫在另一個文件中。
但后來我記得有一個fscanf函數:我讀到了它,但我仍然不完全理解它做了什么以及如何使用它。
在我的情況下,所有整數由空格分隔,我可以寫fscanf(myFile,"%s",word)
嗎? 它會不會考慮''並停在特定字符串的末尾?! 怎么樣?
更重要的是,我可以寫fscanf(myFile,"%d",number)
,它會給我下一個號碼嗎? (我一定是誤會了。感覺像魔術一樣)。
你是對的, fscanf
可以給你下一個整數。 但是,您需要為其提供指針。 因此,您需要一個&
后面的數字:
fscanf(myFile, "%d", &number);
*scanf
系列函數也會自動跳過空格(除非給定%c
, %[
或%n
)。
您的閱讀文件循環最終將如下所示:
while (you_have_space_in_your_array_or_whatever)
{
int number;
if (fscanf(myFile, "%d", &number) != 1)
break; // file finished or there was an error
add_to_your_array(number);
}
旁注:您可能會想到這樣寫:
while (!feof(myFile))
{
int number;
fscanf(myFile, "%d", &number);
add_to_your_array(number);
}
這雖然看起來不錯, 卻有問題 。 如果您確實到達文件末尾,則在測試文件結尾之前,您將讀取垃圾編號並添加到數據中。 這就是你應該首先使用我提到的while
循環的原因。
以下行將完成您的工作,以下行將讀取單個整數。
int number;
fscanf(myFile, " %d", &number);
將它放在循環中直到文件結尾,並將數字放在數組中。
嘗試這個:
#include <stdio.h>
int main(int argc, char* argv[])
{
char name[256];
int age;
/* create a text file */
FILE *f = fopen("test.txt", "w");
fprintf(f, "Josh 25 years old\n");
fclose(f);
/* now open it and read it */
f = fopen("test.txt", "r");
if (fscanf(f, "%s %d", name, &age) !=2)
; /* Couln't read name and age */
printf("Name: %s, Age %d\n", name, age);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.