You should check the return value of scanf
, which tells you the number of data that are read into the passed arguments, here it is k
.
In your case, the return value will be zero as %d
cannot be used to read in a char
in C
. If the first input is a char
it will be 0, 1 if the first value is int
and the second value is a char
, 2 if both of the values are int
.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int n, k, rc;
rc = scanf("%d %d", &n, &k);
if (rc != 2)
{
printf("scanf failed to set the values for n and k
");
}
else
{
printf("valid input for n and k
");
}
printf("%d %d
", n, k);
return 0;
}
So the int k
is uninitialized and thus it will store some random value as scanf
failed to set the value for this variable.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…