2016-12-18 2 views
0

Я пытаюсь сделать простую базу данных с записями из ввода и записать их в файл. Но когда я запускаю программу, она работает только для первой записи. Мне нужно сказать, что файл был создан, и была записана первая запись.Несколько записей с ввода не работают

#include <stdio.h> 

struct produs { 
    char nume[20]; 
    float cantitate,pret_tot,pret_unit; 
    }; 

void main(void) { 
struct produs prod; 
int i; 
char n; 
FILE *fisier; 
fisier = fopen("C:\\Users\\amzar\\Desktop\\Programe PC\\Tema suplimentara\\C_3\\tema_c_3\\fisier.txt","w"); 

printf("\nApasati tasta [d/n] pentru a continua sau nu interogarile!\n"); 
do { 
    printf("\nIntroduceti numele produsului: "); 
    fgets(prod.nume,sizeof(prod.nume),stdin); 
    scanf("%f\n%f\n%f",&prod.pret_unit,&prod.cantitate,&prod.pret_tot); 
    fprintf(fisier,"Numele produsului: %s \nPret unitar: %.2f \nCantitate: %.2f kg \nPret total: %.2f",prod.nume,prod.pret_unit,prod.cantitate,prod.pret_tot); 
} while((n = getche()) != 'n'); 
fclose(fisier); 

}

+0

Что такое 'getche()'? – alk

+0

чтение видимого одиночного символа с ввода –

+0

'getche()' не является частью стандартного Lib. Это опечатка и должна читать 'getch()'? – alk

ответ

0

Ваша проблема происходит, когда вы используете getche() и вы не выбрасывайте \n, что он оставляет на буфере.
Также обратите внимание, что я не использовал fgets, чтобы не включать \n в prod.nume.

Правильный код:

#include <stdio.h> 

struct produs { 
    char nume[20]; 
    float cantitate, pret_tot, pret_unit; 
}; 

void main(void) { 
    struct produs prod; 
    int i; 
    char n; 
    FILE *fisier; 
    fisier = fopen("C:\\Users\\amzar\\Desktop\\Programe PC\\Tema suplimentara\\C_3\\tema_c_3\\fisier.txt","w"); 
    char buffer; 

    do { 
     printf("\nIntroduceti numele produsului: "); 

     /* 
      fgets includes the newline character in the string. 
      this instruction, instead, exlcudes it (%[^\n]) and discard it (%*c) 
     */ 
     scanf("%[^\n]%*c", prod.nume); 
     scanf("%f\n%f\n%f",&prod.pret_unit,&prod.cantitate,&prod.pret_tot); 

     //added '\n' at the end of each struct data 
     fprintf(fisier,"Numele produsului: %s \nPret unitar: %.2f \nCantitate: %.2f kg \nPret total: %.2f\n",prod.nume,prod.pret_unit,prod.cantitate,prod.pret_tot); 

     //input validation for inattentive users 
     do{ 
      //this printf should be before reading the user choice (d/n) 
      printf("\nApasati tasta [d/n] pentru a continua sau nu interogarile!\n"); 

     //here is your error: getche reads the character, but leaves the \n in the buffer... 
     }while((n = getche()) != 'n' && n != 'd'); 

     //...so we have to clean the buffer to not skip next inputs 
     scanf("%c", &buffer); 
    }while(n == 'd'); 

    fclose(fisier); 

} 
+0

спасибо :) это сработало –

+0

Нет проблем! :-) – UrbiJr

Смежные вопросы