2

Suppose I have a hex string that I have calculated from a set of bytes, in a particular format that suits me:

std::string s("#00ffe1"); 

And I less than sign it to std::cout

std::cout << s; //prints: #00ffe1 

Although I like the way cout works, for my purposes it is easier to use fprintf, as this is outputting a formatted string that is just easier with fprintf.

I go to write the same string from fprintf:

fprintf(stdout,"foo=%s",s); // outputs: G* // (i.e., nonsense) 

How do I output this string using fprintf?

2
  • what is wrong with using cout << "foo=" << s;? Commented Jan 31, 2019 at 22:24
  • 1
    @RemyLebeau nothing against it, just becomes a lot when formatting within brackets, braces, and many values Commented Jan 31, 2019 at 22:35

3 Answers 3

5

std::string is a class, not a "string" as the term applies in C (where fprintf comes from). the %s format specifier expects a pointer to a null-terminated array of char []. Use the std::string method c_str() to return the null-terminated-string, and pass that to fprintf:

fprintf(..., s.c_str()); 
Sign up to request clarification or add additional context in comments.

Comments

4

You'll have to convert the std::string to a null-terminated const char* using its c_str() member function:

fprintf(stdout,"foo=%s",s.c_str()); 

Note that this is still C++, even if you use fprintf(). C does not contain a data type std::string.

3 Comments

@bordeo Not really, since a variadic function (one with ... as a parameter) can't really do type-checking at compile-time
Actually, several modern compilers DO now offer compile-time validation of printf-style function parameters, where passing a std::string to %s would be a mismatch that fails validation.
@GovindParmar in the past, I think I got some heads up--a segfault
1

fprintf expects a C-style string, char*. std::string has a c_str() method that returns just that:

fprintf(stdout, "foo=%s", s.c_str()); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.