I'm a beginner who just started to speak the language. The whole number and the mistake are input, but the text is not input and the text is moved on. What's the reason?

Asked 2 years ago, Updated 2 years ago, 21 views

int main()
{
    int a;
    float b;
    char c1;
    printf ("Enter an integer: ");
    scanf("%d", &a);

    printf("Real input : ");
    scanf("%f", &b);

    printf ("Enter characters: ");
    scanf("%c", &c1);

    printf("%d\n %f\n", a, b);
    printf("%c\n", c1);

    return 0;
}

c++

2022-09-20 17:46

2 Answers

The value entered on the keyboard is stored in a place called InputStream and the scanf function reads the value from the input stream.

In this case, the scanf function reads the appropriate value from the input stream by referring to a format format such as %d or %f. However, %c just retrieves one character from the input stream.

The problem with the code you wrote is that in scanf("%f", &b);, the user will type the real number and press the enter key, and the real number and enter value ('\n') will be stored in the input stream. It is then interpreted as "%f" to take the value of the real form in the input stream and store it in b. The input stream will then have an enter value (line break value, '\n').

In this state, the moment scanf("%c", &c1); runs, '\n' remaining in the input stream is stored in c1 and the scanf function ends.

Therefore, in order to avoid this problem, it is recommended in the official document not to write "%c" but to put a space in front of it to "%c". If you put a space in the input stream like this, that space, line breaks, tabs, etc., is absorbed by that space, and you accept one real letter after that character.

The explanation was long, but if you want to get a user input, you can habitually use "%c" in the form of "%c".

Please refer to the code below and the result.

-Code

#include <stdio.h>

int main()
{
    int a; float b; char c1;

    printf ("Enter an integer: ");
    scanf("%d", &a);

    printf("Real input : ");
    scanf("%f", &b);

    printf ("Enter characters: ");
    scanf(" %c", &c1);

    printf("%d\n %f\n", a, b);
    printf("%c\n", c1);

    return 0;
}


2022-09-20 17:46

I didn't know why I couldn't input it, but I changed the %c to %s.

#include <stdio.h>

int main()
{
    int a; float b; char c1;

    Printf. ; ("Enter the integer :")
    scanf("%d", &a);

    Printf. ; ("input error :")
    scanf("%f", &b);

    Printf. ; ("Enter the text :")
    scanf("%s", &c1);

    printf("%d\n %f\n", a, b);
    printf("%c\n", c1);

    return 0;
}


2022-09-20 17:46

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.