Spurious newlines+whitespace when printing substrings in C

%s works properly if your string contains null character ('\0'). If it does not (just like your case), then printf function continues to print characters until it finds '\0' somewhere in memory. Remember that string in C is a character sequence terminated with '\0'. This is the reason why your code does not behave as you expected.

On the other hand, %c prints only one character so you can use:

printf("%c%c", c[0],c[1]);

If you persist in using %s, in this case you have to use %.2s. You probably already know that . shows precision in C. Precision in string means maximum number of characters that you want to print. So usage of .2 results in printing the first two characters in your string. No need to wait for '\0'!

printf("%.2s", c);

I also give @Tom Karzes’s solution. You should change and add these lines:

char c[3];
c[2] = '\0';

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top