2013-12-21 82 views
1

我的代碼下面有問題函數read()我認爲。函數input()沒問題,但是當我使用函數read()進行排序時,文本文件的內容將會出錯。有人能爲我解釋嗎?由於錯誤打印到文本文件

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

void input(); 
void menu(); 
void read(); 

struct product{ 
    char code[20]; 
    char name[50]; 
    int quan; 
    float pr; 
} ; 

void menu() 
{ 

    int k; 
    printf("___________MENU________\n"); 
    printf("1. Enter the info of your products which is saved in Products.txt\n"); 
    printf("2. Read the file Products.txt & sort by price.\n"); 
    printf("3. Exit"); 
    printf("________________________\n"); 
    printf("Enter your option: "); 
    fflush(stdin); 
    scanf("%d", &k); 

    switch(k){ 
case 1: 
    input(); 
    break; 
case 2: 
    read(); 
    break; 
case 3: 
    printf("\nTerminating"); 
    exit(0); 
    break; 
default: 
    printf("\nError!Please Try Again\n"); 
    break; 
}; 
} 


void input() 
{ 
struct product proinfo[50]; 
FILE *fp; 
int i,n; 



if((fp = fopen("Products.txt", "wt")) == NULL) 
    { 
    printf("Error opening file!\n"); 
    exit(0); 
    } 

fprintf(fp,"Code - Name - Quantity - Price (million)\n\n"); 
printf("How many products: "); 
scanf("%d", &n) 
for(i = 0; i < n; i++) 
{ 
    printf("Code of product # %d: ", i + 1); 
    fflush(stdin); 
    gets(proinfo[i].code); 
    fflush(stdin); 
    printf("Name: "); 
    gets(proinfo[i].name); 
    printf("Quantity: "); 
    scanf("%d", &proinfo[i].quan); 
    printf("Price: "); 
    scanf("%f", &proinfo[i].pr); 

} 

if(fp != NULL) 
    { 
    for(i = 0 ; i < n ; i++) 
     fprintf(fp,"%s - %s - %d - %.2f \n", proinfo[i].code, proinfo[i].name, proinfo[i].quan, proinfo[i].pr); 
     fclose(fp); 
    } 

printf("Saving Succesfully"); 
fflush(stdin); 
} 


void read() 
{ 
struct product proinfo[50], temp; 
int i, j, n; 

FILE *fp; 
fp=fopen("Products.txt", "w+t"); 

fprintf(fp,"Code - Name - Quantity - Price (million)\n\n"); 

printf("How many products again: "); 
scanf("%d", &n); 

    for(i=0;i<n-1;i++) 
    { 
     for(j=i+1;j<n;j++) 
     { 
     if(proinfo[i].pr<proinfo[j].pr) 
     { 
      temp=proinfo[i]; 
      proinfo[i]=proinfo[j]; 
      proinfo[j]=temp; 
     }  
     } 
    } 
    //saved into file 
    for(i=0; i < n; i++) 
    { 
     fprintf(fp, "%s - %s - %d - %f \n", proinfo[i].code, proinfo[i].name, proinfo[i].quan, proinfo[i].pr); 
    } 

fclose(fp); 
} 

int main(void) 
{ 
int a; 
for(a=0;;a++) 
{ 
    menu(); 
    getch();  
} 
} 
+0

請問您能解釋一下錯誤是什麼意思?你的意思是命令? – nandu

+0

您可以先不使用標準庫中已經使用的函數的名稱。 –

+1

永遠不要使用'gets' !!它僅存在於向後兼容性中,不應在新代碼中使用。在舊代碼中找到時,應該清除它。 –

回答

0

的2 struct product proinfo[50]在功能input()read()獨立的局部變量。

input()填滿一個,它似乎OP希望在read()存在相同的價值。 (或至少需要從文件中讀取)。

需要使struct product proinfo[50]全局(yeech)或作爲函數參數傳遞。