I am trying to write a code in C language to store the following series of numbers in a string "0.123456789101112131415...".
I am tried this code:
char num[2000], snum[20];;
num[0] = '0';
num[1] = '.';
for(int i = 1; i < 20; i++) {
sprintf(snum, "%i", i);
strcat(num, snum);
printf("%s\n", num);
}
I included the following libraries:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
I get this when I print the variable "num": "0." + some garbage (sometimes I get "0.N", sometime "0.2", sometimes "0.R", and so on).
What am I doing wrong?
As pointed out by David in the comments, strcat requires both strings to have a \0 at the end.
In your case, snum which is being generated by sprintf has the \0. However, num does not.
You could just do num[2] = '\0'. Or something like
sprintf(num, "%i%c\0", 0, '.')
Hope this answers your question.
As David Ranieri stated in the comment, you need a NUL to indicate, so modify the code and you can have the desired outcome
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char num[2000], snum[20];;
num[0] = '0';
num[1] = '.';
num[2] = '\0';
for(int i = 1; i < 20; i++) {
sprintf(snum, "%i", i);
strcat(num, snum);
printf("%s\n", num);
}
}

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With