Add string to char array in C
Solution 1
Look for sprintf
, for example here: Cpp reference
Edit:
sprintf(buf, "My string with args %d", (long) my_double_variable);
Edit 2:
As suggested to avoid overflow (but this one is standard C) you can use snprintf.
Solution 2
snprintf is only C99 not C89, sprintf_s/strcpy_s are only MSVC, not C89, not C99.
char *mystr="come from stdin or file or ...";
char buf[1024];
...
memset(buf,0,sizeof buf);
strncpy(buf,mystr,(sizeof buf)-1);
or non array:
#define BUFLEN 512
char *mystr="come from stdin or file or ...";
char *buf;
...
char *buf=calloc(1,BUFLEN);
strncpy(buf,mystr,BUFLEN-1);
It works on all ANSI C environments.
Solution 3
strcpy(buf, "My String");
Microsoft's compiler also include a function strcpy_s, which is a "safe" version of strcpy. It makes sure that you won't overrun buf
. In this particular case, that's probably not a problem, but you shoul dknow about. But, be aware, it's not available with any other compiler, so it can;t be used where portable is needed.
strcpy_s(buf, sizeof(buf), "My String");
Solution 4
There are many variants, some have been already proposed, some not:
...
char input[] = "My String";
strcpy(buf, input);
strncpy(buf, input, sizeof(buf));
sscanf(input, "%s", buf);
sprintf(buf, "%s", input);
memcpy(buf, input, strlen(input));
...
most of them are unsure/insecure. What exactly should be taken depends on what you really want to do in your code.
Regards
rbo
skylerl
Updated on August 25, 2020Comments
-
skylerl over 3 years
I have a C array called buf. Here is it's definition:
char buf[1024];
Now, my current code takes from
stdin
and usesfgets()
to set that array, however I wish to use code to set it instead. Right now the line that sets buf looks like this:fgets(buf, 1024, stdin);
Basically, I want to replace stdin, with say... "My String". What's the best way to do this?