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

void main ()
{
    char c;
    int choice, dummy;

    do {
        printf ("\n1. Print Hello\n2. Print Javatpoint\n3. Exit\n");
        scanf ("%d", &choice);

        switch (choice)
        {
        case 1:
            printf ("Hello");
            break;
        case 2:
            printf ("Javatpoint");
            break;
        case 3:
            exit (0);
            break;
        default:
            printf ("please enter valid choice");
        }

        printf ("\ndo you want to enter more?");
        scanf ("%d", &dummy);
        scanf ("%c", &c);

    } while (c == 'y');
}

After printf function (do you want to enter more ?) there are 2 more scanf functions. One is taking integer which is stored in dummy and other taking a character.

So when I enter character 'y' , the program runs well.

But when I enter any integer, the program instant terminates itself. But why? Hasn't it left to take a character by another scanf function ?

In short there are two scanf functions, but I can enter 1. why ?

David C. Rankin
  • 81,885
  • 6
  • 58
  • 85
  • The reason: https://stackoverflow.com/questions/5240789/scanf-leaves-the-new-line-char-in-the-buffer – isrnick Oct 24 '21 at 04:09
  • 2
    The basic solution is to add a space before `%c` in the scanf function to clear blank characters before reading a non-blank character: `scanf(" %c",&c);` – isrnick Oct 24 '21 at 04:12
  • 1
    Maybe you should consider learning C from a web site that doesn't name itself after Java? – Karl Knechtel Oct 24 '21 at 04:13
  • 1
    Spend 45 min - 1 hour reading and understanding [man 3 scanf](https://man7.org/linux/man-pages/man3/scanf.3.html). The conversion specifiers that do NOT ignore leading whitespace are `"%[...]"`, `"%c"` and `"%n"`. Taking the time to learn `scanf()` now will save you 100 hours of frustration later.... – David C. Rankin Oct 24 '21 at 04:31
  • Unless you are programming in a *freestanding environment* (without the benefit of any OS), in a standards conforming implementation, the allowable declarations for `main` for are `int main (void)` and `int main (int argc, char *argv[])` (which you will see written with the equivalent `char **argv`). See: [C11 Standard - §5.1.2.2.1 Program startup(p1)](http://port70.net/~nsz/c/c11/n1570.html#5.1.2.2.1p1). See also: [What should main() return in C and C++?](http://stackoverflow.com/questions/204476/) – David C. Rankin Oct 24 '21 at 04:35

0 Answers0