2016-08-14 80 views
1

該代碼目前像一個魅力。但是,最後兩行輸出是相同的,你可以在這裏看到。C編程在編譯器中顯示txt文件

這裏有什麼問題?

數據來自之前構建的txt文件。

1 CADBURY 999 1.900000 
2 PEPSI 999 2.500000 
3 IPHONE 976 2500.000000 
4 SPIRULINA 100 50.000000 
2 PAIPSI 100 0.900000 
10 BLACKMORE 98 30.000000 
17 TROPICANA 13 1.500000 
17 TROPICANA 13 1.500000 

下面的代碼:

#include <stdio.h> 
#include <stdlib.h> 
#include <windows.h> 
#include <ctype.h> 

int addProduct(); 

struct product { 
    int quantity, reorder, i, id; 
    char name[20]; 
    float price; 
}; 

int main() { 
    FILE *fp; 
    int i = 0; 
    struct product a; 

    system("cls"); 

    char checker; 
    int counter; 

    do { 
     fp = fopen("addproduct.txt", "a+t"); 
     system("cls"); 

     printf("Enter product ID : "); 
     scanf(" %d", &a.id); 

     printf("Enter product name : "); 
     scanf(" %s", a.name); 

     printf("Enter product quantity : "); 
     scanf(" %d", &a.quantity); 

     printf("Enter product price : "); 
     scanf(" %f", &a.price); 

     fprintf(fp, "%d %s %d %f\n\n", a.id, a.name, a.quantity, a.price); 
     printf("Record saved!\n\n"); 

     fclose(fp); 

     printf("Do you want to enter new product? Y/N : "); 

     scanf(" %c", &checker); 
     checker = toupper(checker); 

     i++; 

     system("cls"); 
    } while(checker == 'Y'); 

    if (checker == 'N') { 
     fp = fopen("addproduct.txt", "r"); 

     while (!feof(fp)) { 
      fscanf(fp, "%d %s %d %f", &a.id, a.name, &a.quantity, &a.price); 
      printf("%d %s %d %f\n\n", a.id, a.name, a.quantity, a.price); 
     } 
     fclose(fp); 
    } 
    return(0); 
} 

回答

0

while (!feof(fp))不能按預期工作:feof(fp)才成爲真正的輸入失敗。在最後一次迭代期間,fscanf()失敗,但不檢查其返回值,而最後的printf()使用先前迭代中的值。

而應該寫:

while (fscanf(fp, "%d %s %d %f", &a.id, a.name, &a.quantity, &a.price) == 4) { 
    printf("%d %s %d %f\n\n", a.id, a.name, a.quantity, a.price); 
} 
+0

抱歉提問。所以,4是一個隨機數,或者我需要爲它設置一個計數器? –

+0

'4'是'fscanf()':'%d','%s','%d'和'%f'成功執行的轉換次數。 – chqrlie

+0

謝謝你,你搖滾!上帝保佑 :) –

0

當你在你的程序結束時打印出文件的內容,fscanf函數不設置FEOF,直到它嘗試讀取過去的結束的文件。 這意味着在讀取文件的最後一行之後,feof仍然不正確。 因此,循環繼續,然後fscanf嘗試讀取另一行,但失敗。所以變量a.id,a.name等和前一次執行fscanf之後的結果是一樣的。 在打印結果之前,您應該檢查fscanf是否返回了預期的字段數。 例如,

... 如果(的fscanf(fp的, 「%d%S%d%F」,& a.id,a.name,& a.quantity,& a.price)== 4) printf(「%d%s%d%f \ n \ n」,a.id,a.name,a.quantity,a.price); ...

會解決這個問題。

編輯:對不起4個參數不是5,固定

+0

的'fscanf'格式字符串只有4個轉換規格。 – chqrlie

+0

好的。非常感謝你 !上帝保佑:) –