Click here to Skip to main content
14,830,943 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
c
double x = 0.123f;
char s[50] = {0};
sprintf(s, "%lf",x);

but how to spintf "XPosition"+"0.123" ?


What I have tried:

sprintf(s, "%lf","XPositon"+x);
Posted
Updated 11-Jan-19 17:04pm

sprintf works just like printf, but outputs to a string, rather than stdout so
C++
printf("Xposition %lf", x);
becomes
C++
sprintf(s, "Xpostion %lf", x);

sprintf can produce buffer overflows, so better to use snprintf(), instead. e.g.
C++
snprintf(s, 50, "Xposition %lf", x)
. More generally the signature for snprintf is
int snprintf(char *str, size_t size, const char *format, ...);

Note that snprintf() truncates output if it would exceed the designated size, but returns the number of chars it would have written if enough space was available this means you can

C++
if( snprintf(s, 50, "Xpostion %lf" x) > 50) {
    // handle buffer overflow ...
} 
   
Did you try something like:
C++
sprintf(s, "XPositon%lf", x);

Just like with printf.
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900