-5
#include <stdio.h>    

int main() {
    int days = scanf("%d", &days);
    printf("%d", days);
    return 0;
}

The result is 1 no matter what.

7
1

I've used scanf plenty of times and have never encountered this. What's the deal here?

user3643077
  • 29
  • 1
  • 1

2 Answers2

3

This is correct, because, scanf() returns number of successfully matched and converted elements. Considering proper input in your case, every time your input passes the conversion, so you get to see the value 1.

Point to note, scanf() does not return the scanned value itself, it stores the value in the passed argument.

Quoting C11, chapter §7.21.6.4

[...] the scanf function returns the number of input items assigned, which can be fewer than provided for, or even zero, in the event of an early matching failure.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
0

The return type of scanf is to indicate if it successfully read an integer.

This will do what you're expecting

#include <stdio.h>    

int main() {
    int days = 0;
    scanf("%d", &days);
    printf("%d", days);
    return  0;
}
Jack Gore
  • 3,874
  • 1
  • 23
  • 32