Scanf(“%c %f %d %c”) Returning weird values

2020-04-16 02:19发布

问题:

My class assignment asks me to prompt the user to input four variable, char float int char, in one input line.

Here is the entire code:

#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <math.h>

int main(void){
    char h = 'a';
    char b, c, d, e;
    int m, n, o;
    float y, z, x;
    short shrt = SHRT_MAX;
    double inf = HUGE_VAL;

    printf("Program: Data Exercises\n");

    printf("%c\n", h);
    printf("%d\n", h);

    printf("%d\n", shrt);

    printf("%f\n", inf);

    printf("Enter char int char float: ");
    scanf("%c %d %c %f", &b, &m, &c, &y);
    printf("You entered: '%c' %d '%c' %.3f \n", b, m, c, y);

This section of code is where I am having the issue.

    printf("Enter char float int char: ");
    scanf("%c %f %d %c", &d, &z, &n, &e);
    printf("You entered: '%c' %f %d '%c' \n", d, z, n, e);

This part works if I isolate the above section.

    printf("Enter an integer value: ");
    scanf("%d", &o);
    printf("You entered: %15.15d \n", o);

    printf("Enter a float value: ");
    scanf("%f", &x);
    printf("You entered: %15.2f \n", x);

    return 0;
}

Seeing as I cannot post images due to not having a high enough rep, I will provide a link to a screen-cap of the console when running the program.

I would really appreciate if someone could explain to me why the program is not working correctly. Thanks in advance.

回答1:

You have an error in this line:

scanf("%c %d %c %f", &b, &m, &c, &y);

You need to add one space before %c.
Try this line

scanf(" %c %d %c %f", &b, &m, &c, &y);  // add one space %c
scanf(" %c %f %d %c", &d, &z, &n, &e);

This is because after you input the number and press ENTER, the new line stays in the buffer and will be processed by the next scanf.



回答2:

The input of the float value leaves the newline in the input stream. When the next scanf() reads a character, it gets the newline because %c does not skip white space, unlike most other conversion specifiers.

You should also be checking the return value from scanf(); if you expect 4 values and it does not return 4, you've got a problem.

And, as Himanshu says in his answer, an effective way around the problem is to put a space before the %c in the format string. This skips white space, such as newlines, tabs and blanks, and reads a non-space character. The numeric inputs and string inputs automatically skip white space; only %c and %[…] (scan-sets) and %n do not skip white space.



标签: c scanf