Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert int to string and concatenate it in another string (C language)

Tags:

c

strcat

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?

like image 435
Dênis Silva Oliveira Avatar asked Nov 20 '25 04:11

Dênis Silva Oliveira


2 Answers

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.

like image 70
Priyanshul Govil Avatar answered Nov 21 '25 18:11

Priyanshul Govil


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

like image 39
zhangxaochen Avatar answered Nov 21 '25 20:11

zhangxaochen