我有一個檔案.txt,結構是這樣的。 作者,"標題",流派,價格,副本_庫存
。R. 托爾金, "The lords of the rings", Fantasy, 65.50, 31。
我試著使用fgets和scanf
FILE *fp = NULL;
char string[100] 。
char title[30], author[30], genre[30] 。
float 價格。
int copies=0;
fp = fopen("text.txt", "r") 。
while(!feof(fp)) {
fgets(string, 100, fp) 。
sscanf(string, "%[^,] ,%[^,] ,%[^,] ,%f[^,] ,%d[^ ]", autore, titolo, genere, & prezzo, & copie) 。
}
fclose(fp)。
printf("%s %s %s %s %.2f %d
",作者,標題,流派,價格,拷貝)。)
OUTPUT
R. 托爾金 "The lord of the rings"幻想 65,50 0。
為什么它不能訪問變數的副本? 有什么更好的方法嗎?謝謝
uj5u.com熱心網友回復:
這一行的格式指定符是不正確的
sscanf(string, "%[^,],%[^,],%[^,],%f[^,],%d[^ ] ", autore, titolo, genere, & prezzo, &copie)。
它應該是
sscanf(string, "%[^,], %[^,], %[^,],%f,%d", autore, titolo, genere, & prezzo, &copie)。
額外的空格是為了過濾前面的空白--用%[](或用%c)是不自動的。
%f和%d是一種混合的混合體,它們應該是這樣的。這些的轉換在第一個不能使用的字符處停止,沒有你的干預。
旁注:你真的必須檢查scanf()函式族的結果:所做的成功轉換的數量。
uj5u.com熱心網友回復:
"%f[^,]"是合法的,但肯定不是OP想要的。
"%f"掃描一個float,然后"[^,]"掃描該4個字符序列。
有什么更好的方法嗎?
使用" %n"來檢查掃描是否成功。它記錄了掃描的偏移量。
使用寬度限制,如)[^,]中的29,以避免過度填充char陣列.
在)[^,]前使用空格,以消耗可選的前導空白。
錢總是棘手的。
不要使用while(!eof(fp))。 檢查從fgets()的回傳。
char string[100] 。
char title[30], author[30], genre[30] 。
double price;
int copies;
FILE *fp = fopen("text.txt", "r") 。
if (fp) {
while(fgets(string, sizeof string, fp) {
int n = 0;
sscanf(string, " )[^,], )[^,], )[^,],%lf ,%d %n" /span>,
作者,標題,流派,&價格,&拷貝,&n)。
// If n==0, scanning was incomplete
// If string[n], string has extra garbage。
if (n == 0 || string[n]) {
fprintf(stderr, "Bad <%s>
", string)。)
} else {
printf("%s %s %s %s %.2f %d
",作者,標題,流派,價格,拷貝)。)
// Robust code here would do additional work:
///修剪尾部字串的空白。 對數字值進行范圍檢查,等等。
}
}
fclose(fp)。
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/307861.html
標籤:
