Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.5k views
in Technique[技术] by (71.8m points)

c - Passing a non-digit char after an integer to scanf

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

int main(void)
{
  int n, k;
  scanf("%d %d", &n, &k);
  printf("%d %d
", n, k);

  return 0;
}

In the above sample code passing to the input

1 2

Would produce an expected output of

1 2

However passing any char in-between these two digits such as

1. 2 or 1 d 3

Will result in a strange output of the following

1 32766

I would like to know why this occurs, as it was to my belief that scanf would skip over any non-digit input.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...