Hox to use fgets() and getchar() functions? Where is the error in my code?

Hi. I wrote simple code. But it does not work correctly. I could not solve the problem. Entries cannot be right. Please help. (I use gcc 4.9 x86 64 bits)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <stdio.h>

struct _Ogrenci
{
    char ad[30];
    char soyad[30];
    char telefonNumarasi[30];
    char yas[30];
    char adres[100];

};

typedef struct _Ogrenci Ogrenci;

int main(void)
{
    char ch;
    Ogrenci ogrenci;
    FILE *fptr;

    if ((fptr = fopen("deneme.dat", "w")) == NULL)
        printf("\nDosya açılamadı!\n");
    else
    {

        do
        {
            printf("Öğrencinin adı\t\t: ");
            fgets(ogrenci.ad, sizeof(ogrenci.ad), stdin);

            printf("Öğrencinin soyadı\t: ");
            fgets(ogrenci.soyad, sizeof(ogrenci.soyad), stdin);

            printf("Öğrencinin telefon num.\t: ");
            fgets(ogrenci.telefonNumarasi, sizeof(ogrenci.telefonNumarasi), stdin);

            printf("Öğrencinin yaşı\t\t: ");
            fgets(ogrenci.yas, sizeof(ogrenci.yas), stdin);

            printf("Öğrencinin adresi\t: ");
            fgets(ogrenci.adres, sizeof(ogrenci.adres), stdin);

            printf("\nKayıt girmeye devam etmek istiyor musunuz? (E/H) ");
            ch=getchar();

        }while(ch == 'E');

        fclose(fptr);
    }

    return 0;
}
Last edited on
> Entries cannot be right.
¿could you expand on that?
¿how are you checking what you are reading?

¿may you provide an example of your input file?
I do not do any file records. Screen output is below.


Öğrencinin adı          : fd gfds
Öğrencinin soyadı       : fd gfd
Öğrencinin telefon num. : gdf gfd
Öğrencinin yaşı         : gfd gfd
Öğrencinin adresi       : gfd gfd

Kayıt girmeye devam etmek istiyor musunuz? (E/H) E
Öğrencinin adı          : Öğrencinin soyadı     : dfg gfdg             -----> ?
Öğrencinin telefon num. : gfd gfd
Öğrencinin yaşı         : fdg gfdg
Öğrencinin adresi       : dgf

Kayıt girmeye devam etmek istiyor musunuz? (E/H) E
Öğrencinin adı          : Öğrencinin soyadı     : gfdg gfdg           -----> ?
Öğrencinin telefon num. : gfdg gfdg
Öğrencinin yaşı         : gdf gfdg
Öğrencinin adresi       : gfd gfdg

Kayıt girmeye devam etmek istiyor musunuz? (E/H) H
Press <RETURN> to close this window...
After you input your text you press <Return>
Your input buffer would be something line E\ndfg gfdg\n
`getchar()' would take one character, so the input buffer will be \ndfg gfdg\n
So when `fgets()' tries to read, it would stop at the first '\n' giving you an "empty" string.

1
2
ch=getchar();
getchar(); //discarding the newline 
Thank you. I solved the problem by following the link http://stackoverflow.com/questions/17318886/fflush-is-not-working-in-linux
Topic archived. No new replies allowed.