2012-07-18 72 views
-2

我正在看着關於fsacnf的msdn解釋,並試圖更改代碼..這是一場災難,我不明白它是如何工作的。 如果例如我有一個文件x有這樣的信息:「string」 7 3.13'x' 當我寫入scanf(「%s」,& string_input),以便字符串正在保存,然後它轉到下一行? - >到7?我現在會寫: char: char test; fscanf(「%c」,&測試) - 它會跳轉到'x'或取7並將其變成ascii值?fscanf如何與不同的變量類型一起工作?

這裏是我試過的代碼,輸出:

#include <stdio.h> 

FILE *stream; 

int main(void) 
{ 
    long l; 
    float fp,fp1; 
    char s[81]; 
    char c,t; 

    stream = fopen("fscanf.out", "w+"); 
     if(stream == NULL) 
     printf("The file fscanf.out was not opened\n"); 
     else 
     { 
     fprintf(stream, "%s %d %c%f%ld%f%c", "a-string",48,'y', 5.15, 
       65000, 3.14159, 'x'); 
    // Security caution! 
    // Beware loading data from a file without confirming its size, 
    // as it may lead to a buffer overrun situation. 
    /* Set pointer to beginning of file: */ 
    fseek(stream, 0L, SEEK_SET); 

    /* Read data back from file: */ 
    fscanf(stream, "%s", s); 
    fscanf(stream, "%c", &t); 
fscanf(stream, "%c", &c); 

    fscanf(stream, "%f", &fp); 
    fscanf(stream, "%f", &fp1); 
    fscanf(stream, "%ld", &l); 



    printf("%s\n", s); 
    printf("%c\n" , t); 
    printf("%ld\n", l); 
    printf("%f\n", fp); 
    printf("%c\n", c); 

    printf("f\n",fp1); 
    getchar(); 


    fclose(stream); 
    } 
} 

這是輸出:

 
a-string 

-858553460 
8.000000 
4 
f 

無法爲什麼

感謝理解!

+0

點擊下一步你的選擇答案。 – hmjd 2012-07-18 13:21:58

回答

1

缺少格式說明:

printf("f\n",fp1); 

應該是:

printf("%f\n",fp1); 

更重要的是:檢查fscanf()返回值。它返回成功分配的數量:對於每個呼叫,它應該是1,因爲每個fscanf()呼叫應該只有一個分配。如果fscanf()失敗,則該變量未修改。在代碼中的變量未初始化,如果fscanf()無法分配給他們,他們將包含隨機值,這是這裏的情況:

      /* a-string 48 y 5.15 65000 3.14159 x */ 
fscanf(stream, "%s", s); /*^   (s is assigned "a-string") */ 
fscanf(stream, "%c", &t); /*  ^ (t is assigned space)  */ 
fscanf(stream, "%c", &c); /*  ^ (c is assigned 4)   */ 
fscanf(stream, "%f", &fp); /*   ^ (fp is assigned 8)   */ 
fscanf(stream, "%f", &fp1); /*   ^(fail: 'y' is not a float) */ 
fscanf(stream, "%ld", &l); /*   ^(fail: 'y' is not a long) */ 
+0

不錯的格式化! – MvG 2012-07-18 13:34:42

1

你寫的聲明是

「%s%d %C%F%LD%F%C」, 「A-串」,48, 'Y',5.15,65000,3.14159, 'X'

如果打印第五個參數作爲%ld那麼應該也通過它作爲(long)65000。但在大多數系統中,這不會有什麼區別。該文件的內容現在看起來應該和得到解析如下:

a-string 48 y5.15650003.14159x 
^  ^^^ 
s  |c| 
     t fp 

s: "a-string" 
t: ' ' 
l: undefined 
fp: 8 
c: '4' 
fp1: undefined 

所以s的第一個字相匹配,到第一個空間。 t與空格字符匹配,因爲%c不會跳過前導空格。 c48的第一個數字和fp的第二個數字匹配。對於fp1%f將跳過下一個空格,然後無法讀取任何內容,因爲字符y不能被讀爲浮點數。 %ld對於%l將出於同樣的原因失敗。您應檢查fscanf的結果以檢測並報告此類錯誤。

相關問題