Paradox
Paradox

Reputation: 19

C/C++ printf() and scanf() reversed when running the program

Here is my code:

#include <stdio.h>
#include <stdlib.h>
enum abcd{aaaa,bbbb,cccc,dddd,z};

typedef struct stct{
    abcd eAbcd;
    int x;
} stct;
typedef struct indexx{
    int size;
    struct stct *addr;
} indexx;

void add_item(indexx *idx);
stct read_in();

int main()
{
    indexx idx = {0, NULL};
    int op;
    while (1)
    {
        printf("\n1. add item\n4. quit\n");
        scanf("%d\n", &op);
        switch (op)
        {
            case 1:
                add_item(&idx);
                break;
            case 4:
                return 0;
            default:
                printf("Please enter a correct number\n");
        }
    }
}

void add_item(indexx *idx)
{
    stct *newdata;
    newdata = (stct *) realloc(idx->addr, idx->size*sizeof(stct));
    if (newdata)
    {
        idx->size ++;
        idx->addr = newdata;
        idx->addr[idx->size-1] = read_in();
    }
    else
        printf("No memory\n");
}

stct read_in()
{
    stct temp;
    int ab;
    temp.eAbcd = z;
    while (temp.eAbcd != aaaa && temp.eAbcd != bbbb && temp.eAbcd != cccc && temp.eAbcd != dddd)
    {
        printf("select(1-4):\n");
        scanf("%d", &ab);
        ab-=1;
        switch (ab)
        {
            case 0: temp.eAbcd = aaaa; break;
            case 1: temp.eAbcd = bbbb; break;
            case 2: temp.eAbcd = cccc; break;
            case 3: temp.eAbcd = dddd; break;
        }
    }
    scanf("%d", &temp.x);
    return temp;
}

It was supposed to print out select(1-4): before scanf(), but when I compile and run the program, I got this:

1
select(1-4):

(1is what I entered.)

I have tried the solutions in C/C++ printf() before scanf() issue and none of them works for me.

Upvotes: 0

Views: 452

Answers (1)

user2371524
user2371524

Reputation:

Your problem is in this line:

    scanf("%d\n", &op);

The \n here is just a whitespace character (like and \t) and scanf() treats any whitespace character the same: They match a sequence of whitespace in the input stream of any length (including 0).

If you enter a number and hit enter, you do enter a newline and this newline is indeed matched by \n, it would also be matched by or \t. But you don't want to match it: stdin is by default line buffered, and as scanf() would optionally match more whitespace characters, it will wait for more input to see whether more whitespace is following and only return once you hit enter again because with line buffering, input only becomes available at a newline.

In a nutshell: This scanf() won't complete until you hit enter again, so add_item() isn't even called until you do.

The simple solution here: remove the bogus \n from the format string.

Upvotes: 1

Related Questions