Daniel Toh
Daniel Toh

Reputation: 23

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?

Upvotes: 0

Views: 91

Answers (1)

Sourav Ghosh
Sourav Ghosh

Reputation: 134396

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. [....]

Upvotes: 5

Related Questions