简体   繁体   中英

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

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM