Help with c language?

include <stdio.h>

int main()

{

char nama[40];

int nim;

char jk;

printf("Nama:"); scanf("%[^\n]",nama);

printf("Nim:"); scanf("%d",&nim);

printf("Jenis Kelamin (L/P):");

jk=getchar();

return 0;

}

can anybody explain why the jk=getchar(); command doesn't work?? why?? hot to fix it? 10 points if works

3 Answers

Relevance
  • Anonymous
    1 decade ago
    Favorite Answer

    Hm....

    After get scan from console, flush stdin (clear buffer).

    u can see what this happen

    printf("Nama:"); scanf("%[A-Za-z]",nama);

    fflush(stdin);

    printf("Nim:"); scanf("%d",&nim);

    fflush(stdin);

    printf("Jenis Kelamin (L/P):");

    jk=getchar();

  • 1 decade ago

    My guess: There is still content buffered on the command line, which is consumed by getchar().

    When I added the following to your code

    printf("Content of jk: >>>%c<<<", jk);

    the <<<< ended up on the next line.

    I also tried to flush input/output, (fflush(stdin), fflush(stdout). I could not get it working.

    ------

    cucu-Nya: I tried your code, just adding an output function (printf). This code did not print anything captured by jk; I am using Netbeans IDE 6.7.

    char nama[40];

    int nim;

    char jk;

    printf("Nama:"); scanf("%[A-Za-z]",nama);

    fflush(stdin);

    printf("Nim:"); scanf("%d",&nim);

    fflush(stdin);

    printf("Jenis Kelamin (L/P):");

    jk=getchar();

    printf("%c", jk);

  • 1 decade ago

    What I would expect is that the program halts on that line until a key is pressed, at which point the program exits. Are you expecting something different, and if so why?

Still have questions? Get your answers by asking now.