简体   繁体   中英

Program doesn't print character when I enter a string

So I have this code:

#include <stdio.h>
int main() {
    char B,y[2];
    scanf("%c",&B);
    scanf("%s",y);
    printf("%c\n",B);
}

When I enter in a character for B like S , then a character for y like a , it works fine. It prints out

a
S

However, when I enter 2 characters for y like ab , it prints the two characters but doesn't print out S . It prints:

ab

Am I doing something wrong?

First of all, a char array, defined like y[2] can hold only one char and the other space is reserved for terminating null for that array to behave as string . In other words, the max length of the string it can hold is only 1.

That said, as per the understanding, you should change

 scanf("%s",y);

to

 scanf("%1s",y);

to limit the input length. Otherwise, you'll experience buffer overflow which invokes undefined behavior .

To elaborate on adding that literal 1 in the format string, that 1 denotes the maximum field width .

Quoting C11 , chapter §7.21.6.2, fscanf() , ( emphasis mine )

An input item is read from the stream, unless the specification includes an n specifier. An input item is defined as the longest sequence of input characters which does not exceed any specified field width and which is, or is a prefix of, a matching input sequence. [....]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM