Search code examples
carraysstringcharfgets

Add string to char array in C


I have a C array called buf. Here is it's definition:

char buf[1024];

Now, my current code takes from stdin and uses fgets() 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?


Solution

  • 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.