0

Hello, all.
I'm looking through the code I'm altering for MFC, and I found these variable printf lines.

printf("%s%s","|Val=",outString);

and

printf("|type = 0x%x\n", type);

Of course I understand how the latter one works, but the former is confusing. It seems to output just like the second variation, even though the order of input is reversed.
Why do they both do (what appears to be) the same thing?

If I want to concatenate a version of the first format to the end of an existing string, do I have to change the order drastically for a successful sprintf, or just work with it as is?

2
Contributors
1
Reply
2
Views
12 Years
Discussion Span
Last Post by Ancient Dragon
0

I would have written the first one like this

printf("|Val=%s",outString);

but if your goal is to concantinate two strings into a single buffer

char buf[255];

strcpy(buf,"|Val=";
strcat(buf,outString);

//or (same as above)
sprintf(buf,"|Val=%s",outString);

Neither of the above two are safe because neither strcat() nor sprintf() check for buffer overflow. Since you are using MFC you must also be using a c++ compiler. And in that case you should probably convert the code to c++ where it will be safer

std::string buffer;
buffer = "|Val=";
buffer += outString; // if outString is std::string then 
                            // you can combine the above 2 lines

;

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.