kimiko88
kimiko88

Reputation: 60

C: scanf for a single char with formatter %s

I see that when I use that code:

char c,d;
scanf("%s",&c);
scanf("%s",&d);
printf("%c%c",c,d);

seems fix the problem of save ENTER character in d variable.

It's a good way or compiler add the string terminator in the memory address next to c variable (equals for d variable)?

Upvotes: 1

Views: 320

Answers (2)

John Bode
John Bode

Reputation: 123458

%s expects its argument to point to the first element of an array of char wide enough to hold the input string plus the 0 terminator, so if you want to read a single input character using %s then the target must be an array at least two elements wide:

char c[2];
scanf( "%s", c ); // no & operator since c is an array in this case

%s tells scanf to skip over any leading whitespace, read the next sequence of non-whitespace characters up to (but not including) the next whitespace character, so it will not read and store the trailing newline character in c1.

If you type SpaceAEnter, then your input stream will contain the sequence { ' ', 'A', '\n' }. scanf will read and discard the leading blank, read 'A' into c, stop reading at '\n', then terminate the string in c, so when all is said and done the input stream contains { '\n' } and c contains { 'A', 0 }.

%c reads and stores individual characters as you've done here. It also does not skip whitespace characters, which is why you can store the newline character with it.

Putting everything together, you could do something like this:

char c[2], d;
scanf( "%1s", c );
scanf ("%c", &d );

which will consume both your input character and the newline.


  1. For safety's sake, we should use the conversion specifier %1s to tell scanf to read no more than one character into c.

Upvotes: 1

Govind Parmar
Govind Parmar

Reputation: 21532

No, because it will also want to null-terminate the string. In other words, write to *(d + 1) (at least!), and that's undefined behavior (namely, overflow).

Upvotes: 2

Related Questions