0

I want to wrote a program with menu and in case the user select 1 until 4 i have simple switch:

int main() {

    char str1[127];
    char str2[127];
    int result;
    int option = 0;

    while (option < 1 || option > 4)
    {
        printoptions();
        scanf("%d", &option);

        switch (option)
        {
        case 1:

            printf("Please enter first string: ");
            gets(str1);

            printf("Please enter second string: ");
            gets(str2);

            // bla bla

            break;

        case 2:
            break;

        case 3:

            break;

        case 4:
            break;

        default:
            break;
        }
    }

    printf("\nPress any key to continue");
    getch();
    return 0;
}

So my problem here is that after the user select the option 1 i can see this output:

Please enter first string: Please enter second string:

Why this is happening ?

user979033
  • 5,430
  • 7
  • 32
  • 50
  • 3
    Don't use `gets`. Don't *ever* use it! It is a dangerous function, and for that reason have been removed from the C standard. Use e.g. [`fgets`](http://en.cppreference.com/w/c/io/fgets) instead. – Some programmer dude Nov 06 '17 at 09:26
  • OK but if i use scanf and the user input is "test " i can see the the input in only "test' without the empty space – user979033 Nov 06 '17 at 09:27
  • 2
    @user979033 use [`fgets`](https://www.tutorialspoint.com/c_standard_library/c_function_fgets.htm) – Ajay Brahmakshatriya Nov 06 '17 at 09:28
  • 1
    `scanf("%d")` doesn't consume the newline character generated when you press `Enter` after the number. It is consumed by the first `gets()` that reads an empty string this way. – axiac Nov 06 '17 at 09:28
  • 1
    Mixing `scanf` and `fgets` is a bad idea. And so is using `scanf` for user input. – Jabberwocky Nov 06 '17 at 09:29
  • https://stackoverflow.com/a/5240807/1023911 – Werner Henze Nov 06 '17 at 09:31
  • 1
    Generic links: [How to read / parse input in C? The FAQ](https://stackoverflow.com/q/35178520/2371524) and [A beginners' guide away from `scanf()`](http://sekrit.de/webdocs/c/beginners-guide-away-from-scanf.html). Next time have a look at the [tag wiki](https://stackoverflow.com/tags/c/info) first. And repeating earlier comments here: **don't EVER use `gets()`!!** –  Nov 06 '17 at 09:32
  • @FelixPalmen that is true. I think OP needs better error handling in that case. – Ajay Brahmakshatriya Nov 06 '17 at 09:35

0 Answers0