Reputation: 69
I have a simple program that reads a pair of characters from a char[]
array and prints each pair to the console, all on the same line - for some reason, some spurious newlines (and whitespace) are added to the output.
I've removed usage of str libs (apart from strlen
) that may add newlines at the end of strings - but I am still lost as to what's happening.
The program:
#include <stdio.h>
#include <string.h>
char input[] = "aabbaabbaabbaabbaabb";
int main() {
int i;
char c[2];
size_t input_length = strlen(input);
for (i=0; i<input_length; i+=2) {
c[0] = input[i];
c[1] = input[i+1];
printf("%s", c);
}
printf("\n");
return 0;
}
Expected output:
aabbaabbabbaabbaabb
Output:
aabbaabbabb
aa
bbaabb
Why are there newlines and whitespace in the output? (Note that the 1st line has a single a
towards the end - could not deduce why)
Using Apple clang version 11.0.0 (clang-1100.0.33.16), though I would doubt if that matters.
Upvotes: 0
Views: 123
Reputation: 857
%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';
Upvotes: 1