3

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?

2 Answers2

1

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.

Priyanshul Govil
  • 518
  • 5
  • 20
1

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);
    }
}

enter image description here

zhangxaochen
  • 32,744
  • 15
  • 77
  • 108