Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C - Format char array like printf

I want to format a c string like printf does. For example:

char string[] = "Your Number:%i";
int number = 33;
// String should now be "Your Number:33"

Is there any library or a good way I could do this?

like image 491
Felix Scheinost Avatar asked May 30 '12 16:05

Felix Scheinost


1 Answers

Use sprintf(char* out, const char* format, ... ); like so:

int main() {
  char str[] = "Your Number:%d";
  char str2[1000];
  int number = 33;
  sprintf(str2,str,number);
  printf("%s\n",str2);
  return 0;
}

Output:

---------- Capture Output ----------
> "c:\windows\system32\cmd.exe" /c c:\temp\temp.exe
Your Number:33

> Terminated with exit code 0.
like image 147
dcp Avatar answered Oct 01 '22 03:10

dcp