2017-02-19 70 views
-2

掃描並從數據庫打印第一行後,此代碼崩潰。我真的找不到解決辦法。掃描/打印第一行後代碼崩潰

崩潰的一個鏡頭:數據庫的

Crash

內容:

Matthew Summers 53901523 256325 135500 
Jacob Sutherland 52392302 723232.2 1200000 
Michael Phelps 58238211 971000.52 653350 
Aaron Gordon 59923325 325700.92 623320 
Vasil Maglaperidze 59952323 189900.32 330000 
Avtandil Shoshiashvili 95234322 432000.72 723023 
Michael Jordan 35252372 120899.75 50000 
Daniel Whiteman 85238202 178500.53 349800 
James Oneal 98773235 90750.23 197050 
Haytheim Russels 19326233 178250.22 221580 

我的代碼:

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 

#define CHAR_BUF 128 
#define DATA_FILE "database.txt" 

typedef struct client 
{ 
    char fname[CHAR_BUF]; 
    char lname[CHAR_BUF]; 
    int pnumber; 
    float wins; 
    float loses; 
    float ratio; 
}client; 

int ReadData(FILE *fp); 

int main() 
{ 
    //int lines=0; 
    //client client[i]; 
    FILE *fp = fopen(DATA_FILE, "r"); // opens file 
    if(fp==NULL) // checks if .txt file is empty 
    { 
     printf("Database is empty."); 
     exit(1); 
    } 
    ReadData(fp); // Calls function to read db 
    //lines = ReadData(fp); 
    //printf("Line amount: %d", lines); 
} 


/* This function reads data from database 
* and assigns values to their variables 
*/ 
int ReadData(FILE *fp) 
{ 
    int i=0; 
    client client[i]; 
    while(!feof(fp)) 
    { 
     fscanf(fp, "%s %s %d %f %f", client[i].fname, client[i].lname, 
     &client[i].pnumber, &client[i].wins, &client[i].loses); 
     printf("%s %s %d %.2f %.2f\n", client[i].fname, client[i].lname, 
     client[i].pnumber, client[i].wins, client[i].loses); 
     i++; 
    } 
    return i; 
} 
+1

使用正確的工具來解決這些問題是你的調試器。在*堆棧溢出問題之前,您應該逐行執行您的代碼。如需更多幫助,請閱讀[如何調試小程序(由Eric Lippert撰寫)](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)。至少,您應該\編輯您的問題,以包含一個[最小,完整和可驗證](http://stackoverflow.com/help/mcve)示例,該示例再現了您的問題,以及您在調試器。 –

+1

爲什麼標記爲C++? – Biffen

+1

'客戶端客戶端[i];''客戶端客戶端[0];' – BLUEPIXY

回答

0
  1. int i=0; 
    client client[i]; 
    

    這將創建一個大小0的數組
    將其更改爲(不作任何意義。):

    #define MAX 30 
    
    client client[MAX]; 
    
  2. while(!feof(fp)) 
    

    當最後一個記錄已被從文件中讀取最後還有\n。所以,當這個表達式得到評估feof(fp)返回FALSE,因爲它不是文件的結尾。
    但在下一行fscanf(fp, "%s %s %d %f %f", client[i].fname, client[i].lname, &client[i].pnumber, &client[i].wins, &client[i].loses);它的eofscanf失敗。
    這解釋了最後一個垃圾行。
    解決方案:
    檢查是否scanf成功與否,如果它確實然後只執行printf

    while(fscanf(fp, "%127s %127s %d %f %f", client[i].fname, client[i].lname, &client[i].pnumber, &client[i].wins, &client[i].loses) == 5) 
    {  
        printf("%s %s %d %.2f %.2f\n", client[i].fname, client[i].lname, client[i].pnumber, client[i].wins, client[i].loses); 
        i++; 
    } 
    
+0

非常感謝。這是完美的。 ojaxis tkvnis survilebit, Levan –