Reputation: 741
I'm using the below code to convert an array of characters to a string C. However the output is different from what I expected.
#include<stdio.h>
int main()
{
char data[5] = {
'a', 'b', 'c', 'd', '\0'
};
char buff[100];
int i = 0;
while (data[i] != '\0')
{
printf("%c Character here \n", data[i]);
snprintf(buff, 100, "%s", & data[i]);
printf("%s String here\n", buff);
i++;
}
}
The result I expect is
a Character here
a String here
b Character here
b String here
c Character here
c String here
d Character here
d String here
However I'm getting this as output
a Character here
abcd String here
b Character here
bcd String here
c Character here
cd String here
d Character here
d String here
Can somebody explain this?
Upvotes: 0
Views: 1553
Reputation: 5325
data
is already a string, since it is a null-terminated sequence of characters (which is what a string is in C).
You are getting those results because you are calling snprintf
inside a loop over data
.
First you call snprintf()
on &data[0]
, which copies data
into your buffer from data[0]
until it reaches the null. Then you call snprintf()
on data[1]
, which copies into your buffer from &data[1]
until it reaches the null. And so on...
And each time you do so, you call printf()
on the buffer, with a %s
parameter... which prints the argument as a sequence of characters until it reaches the terminating null (i.e. %s
prints a string).
If you want to print a single character, use %c
. If you want to print to the buffer character by character until you reach the null, do it manually - but snprintf()
is designed so that you don't have to do that.
Using snprintf()
in a more common manner:
#include<stdio.h>
int main() {
char data[5] = {'a', 'b', 'c', 'd', '\0'};
// or char data[] = "abcd";
char buff[100] = {0};
snprintf(buff, sizeof buff, "%s", data);
printf("%s String here\n", buff);
return 0;
}
Copy/print each character manually:
#include<stdio.h>
int main() {
char data[5] = {'a', 'b', 'c', 'd', '\0'};
// or char data[] = "abcd";
char buff[100] = {0}; // initialises buff by filling it with zeroes
char *ptr = data, *buff_ptr = buff;
while (*ptr) {
*buff_ptr = *(ptr++);
printf("%s current\n", buff_ptr++);
printf("%s from the start\n", buff);
}
return 0;
}
Upvotes: 7