Why am I having problems with scanf and it turns out?

when I try to use scanf and it gets, I have problems, I need to put it twice, if I put it as soon as my program is finished, this is homework, and I have to use these functions in these places.

the code:

int main()  
{
    int i=0,operation=0;
    char str[100];

    printMenu();

    scanf("%d",&operation);

    switch (operation)
    {
        case 1:     
            printf("Please, enter your sentence >");
            gets(str);
            gets(str);

            if (checkChars(str))
                inputSent(str);
            else
                printf("ERROR: Incorrect data, try again.");

            break;
    }   

    return 0;
}
+3
source share
2 answers

So we have a stdin data stream. This is the input you write on the terminal.

When you call scanf, it reads only the decimal number that you wrote. After it, he does not read a new line. Therefore, you need two calls gets, because the first call sees only '\n', and the second sees your actual data.

, , sscanf .

:

printMenu();

gets(str)
sscanf(str, "%d", &operation);

switch (operation) {
+1

scanf(), , ( , , , ), gets(), , "enter", . , . , . , , ( scanf()):

while (getchar() != EOF);
, , , . , , .

0

Source: https://habr.com/ru/post/1776326/


All Articles