Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.6k 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...