Bauer
Bauer

Reputation: 159

Why is my second "scanf" being skipped?

This is in my main function..

    printf("How many marking components in the course? ");
    scanf("%d", &numberOfComponents );
    for (int i=0; i<numberOfComponents; i++){

            char c[MAX_STR];
            printf("enter next component name: ");
            fgets(c, sizeof(c), stdin);
            scanf(c, " %c", &c);


            Component comp;

            initComp(&comp, c);
            class.comps[i] = comp;

            }

    printf("How many marking schemes? ");
    scanf(" %d", &numberOfSchemes);

I have tried the white space but it still persists

Upvotes: 0

Views: 347

Answers (2)

Jonathan Leffler
Jonathan Leffler

Reputation: 755064

You should test that your input operations worked; things go haywire when you don't.

This call to scanf():

scanf(c, " %c", c);

should (as chux diagnoses in his answer) be written differently, but I think it should be more like:

char filler;
if (scanf(" %c", &filler) != 1)
    …report problem…

The original version uses the line that was just read as the format string, and it is almost certain to fail matching the second input. If you simply use scanf(" %c", c), which is the simplest edit, then you overwrite the first character of the line of input with the next non-blank character.

There's then the question of why you're making the user enter the extra data after the component name. They have to enter something. On the next fgets(), the code will read after the first character up to the next newline. So, if you typed:

component-1
component-2

The first fgets() would read component-1 and the newline; the scanf() as amended would read the c of component-2 into c[0], and then the next fgets() would read omponent-2 plus the newline into c on the next iteration.

You could see more of what is going on by adding code to print what you read as you read it:

printf("Line 1: [[%s]]\n", c);  // after the fgets()
printf("Line 2: [[%s]]\n", c);  // after the scanf()

This is one of the most basic of debugging techniques; echo what you've read to make sure the program got the data you think it got.

Upvotes: 1

chux
chux

Reputation: 154582

Mixing fgets() with scanf() often causing problems.

scanf("%d"... leaves any following white-space like '\n' in stdin for fgets() to get. The same happens after scanf(c, " %c", &c); (which likely was meant to be scanf(" %c", c); or sscanf(c, " %c", c);).

scanf("%d", &numberOfComponents );
...
fgets(c, sizeof(c), stdin);

Recommend using only fgets() to get user input and use sscanf(), strtol(), etc. to parse that input.

fgets(c, sizeof(c), stdin);
sscanf(c, "%d", &numberOfComponents );

....

fgets(c, sizeof(c), stdin);
// I do not think you need the following line of code.
// Besides it is UB as it attempts to scan and save into the same buffer.
// sscanf(c, "%c", &c );  

Error checking of the result of fgets(), sscanf() omitted, but still good to do.

Upvotes: 0

Related Questions