Home > Enterprise >  Remove format specifiers from printf
Remove format specifiers from printf

Time:10-31


I want to use printf to output a text.

If I want to print a text which has previously entered by the user and may contain a %, the output is a garbled mess. This is propably due to % being a format specifier in printf, but no value/argument is given.

For example:

std::string inputString = "% Test";
printf(inputString.c_str());

Output:  6.698271e-308st

Desired output would be: % Test

Is there an elegant way to avoid this? Entering %% instead of % works, but it's obviously not very user-friendly.

The only other way I see is modifying the input string to automatically replace every single % with %%. But is this the way to go? I'm specifically want/need to use printf, using cout is not possible

CodePudding user response:

Either you use this:

printf("%s", string.c_str());

Or you use the one that doesn't do formatting at all:

puts(string.c_str());

Note, that puts always adds a newline though!

Edit: Added c_str to not cause confusion with the actual question.

CodePudding user response:

prints always takes a format string as the first parameter. You cannot change that. However, you can use it to specify that it should just print a string passed as the second argument as is.

std::string inputString = "% Test";
printf("%s", inputString.c_str());

Note that, while there is no restriction of what char array you can pass as the format string, you should not use strings provided by a user, even if you don't expect any funny characters in it. It creates an exploitable vulnerability.

Usually, it's the best to use a string literal. It allows the compiler to warn you if you pass incorrect types of arguments. (Compilers don't have to check that but they often do.)


Maybe I should mention that printf is a C function. While using it in C program is entirely fine, you could consider switching to C style streams from the header <iostream>. They have advantages and disadvantages but I think in your case they would be easier to use, especially that they support std::string.

#include <iostream>
#include <string>

int main(){
    std::string inputString = "% Test";
    std::cout << inputString;
}

CodePudding user response:

printf,when used with the %s format specifier, requires a pointer to char. You can get that from an std::string via the c_str() method:

std::string inputString = "% Test";
printf("%s", inputString.c_str());
  • Related