Scanf inside the printf

Asked

Viewed 455 times

-1

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

int main()
{
    int i;
    printf("digite um número %d",scanf("%d",&i));

}

The following program only gives the result 1 and I do not understand why.

  • You can select the code snippet and press ctrl+k to leave formatted.

1 answer

2

Because the Scanf returns an integer with the amount of entries.

scanf("%d",&i) 

This will return number 1

scanf("%d" "%d",&p,&i) 

Will return the number 2 and so on.

If you put inside a while, as follows:

while ( scanf("%d", &i) == 1) 

It will be true. If you put

while ( scanf ("%d" "%d", &p, &i) == 2) 

Will be true also.

And so on and so forth.

  • In C it is correct to concatenate strings separating them with space, now this is not traditional to see. In your example, in reading two integers, I would expect to find "%d %d", nay "%d" "%d". Again, it’s not wrong, it’s just not very usual to find this concatenation in family operations scanf and printf

Browser other questions tagged

You are not signed in. Login or sign up in order to post.