How to add a char/int to an char array in C?

后端 未结 5 872
感情败类
感情败类 2020-12-14 02:58

How can I add \'.\' to the char Array := \"Hello World\" in C, so I get a char Array: \"Hello World.\" The Question seems simple but I\'m struggling.

Tried the follo

5条回答
  •  隐瞒了意图╮
    2020-12-14 03:23

    The error is due the fact that you are passing a wrong to strcat(). Look at strcat()'s prototype:

       char *strcat(char *dest, const char *src);
    

    But you pass char as the second argument, which is obviously wrong.

    Use snprintf() instead.

    char str[1024] = "Hello World";
    char tmp = '.';
    size_t len = strlen(str);
    
    snprintf(str + len, sizeof str - len, "%c", tmp);
    

    As commented by OP:

    That was just a example with Hello World to describe the Problem. It must be empty as first in my real program. Program will fill it later. The problem just contains to add a char/int to an char Array

    In that case, snprintf() can handle it easily to "append" integer types to a char buffer too. The advantage of snprintf() is that it's more flexible to concatenate various types of data into a char buffer.

    For example to concatenate a string, char and an int:

    char str[1024];
    ch tmp = '.';
    int i = 5;
    
    // Fill str here
    
    snprintf(str + len, sizeof str - len, "%c%d", str, tmp, i);
    

提交回复
热议问题