Welcome to JiKe DevOps Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
229 views
in Technique[技术] by (71.8m points)

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

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
", 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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

Please log in or register to answer this question.

1 Answer

0 votes
by (71.8m points)

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] = '';
    
    for(int i = 1; i < 20; i++) {
        sprintf(snum, "%i", i);
        strcat(num, snum);
        printf("%s
", num);
    }
}

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to JiKe DevOps Community for programmer and developer-Open, Learning and Share
...