Click here to Skip to main content
13,828,483 members
Rate this:
 
Please Sign up or sign in to vote.
See more:
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 3 days ago
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 1

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

sprintf can produce buffer overflows, so better to use snprintf(), instead. e.g.
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

if( snprintf(s, 50, "Xpostion %lf" x) > 50) {
    // handle buffer overflow ...
} 
   
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 2

Did you try something like:
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)

  Print Answers RSS
Top Experts
Last 24hrsThis month


Advertise | Privacy | Cookies | Terms of Service
Web03 | 2.8.190114.1 | Last Updated 11 Jan 2019
Copyright © CodeProject, 1999-2019
All Rights Reserved.
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100