Yogesh Satyam
Yogesh Satyam

Reputation: 33

why following code is not taking all inputs?

#include <stdio.h>
int main()
{
   int a;
    float b;    
    char ch;
    
        scanf("%d%f%c",&a,&b,&ch);
        printf("%d %f %c",a,b,ch);
    return 0;
}

whenever I run above code

its takes only two inputs and terminates why is that? I want to input :2,3.5,d.but its terminates after 3.5.

here is image of when I run the code: https://i.sstatic.net/ef6CE.png

Upvotes: 0

Views: 71

Answers (2)

Aryan Garg
Aryan Garg

Reputation: 11

Include spaces in format string. Otherwise any whitespace character (spaces, newline and tab characters) will be read into your variables. So, include a space before %c like this:

scanf("%d%f %c",&a,&b,&ch);

Upvotes: 1

Martian
Martian

Reputation: 94

I think that the problem is the fact that you do not have a whitespace between the "%f" and %c" conversion specifiers, and without it after the "%f" scanf() consumes the newline character as the given character.

this might help you https://man7.org/linux/man-pages/man3/scanf.3.html

As a matter of a fact, I placed a whitespace between the "%f" and "%c", and the following program seems to work on https://www.onlinegdb.com/online_c_compiler

#include <stdio.h>

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

    scanf("%d%f %c",&a,&b,&ch);
    printf("%d %f %c",a,b,ch);
    return 0;
}

Furthermore, if you print your data using parenthesis 'printf("(%d %f %c)",a,b,ch); you will see the consuming of the newline character for yourself.

The output of the original program, without the whitespace between %f, %c:

2
3.5
(2 3.500000 
)

The output of the edited program, with the whitespace between %f, %c:

2
3.5
x
(2 3.500000 x)

Upvotes: 0

Related Questions