Search code examples
c++printfstring-literals

printf - raw string literal with format macro of fixed width integer types


How do I use raw string literal R with format macro of fixed width integer types?

For example

std::int64_t num = INT64_MAX;
std::printf(R"("name":"%s", "number":"%")" PRId64, "david", num); // wrong syntax

The output should be

"name":"david", "number":"9223372036854775807"

Use of escape sequences instead of R is not permitted


Solution

  • Firstly, you should check your current format string with puts().

    #include <cstdio>
    #include <cinttypes>
    
    int main(void) {
        std::puts(R"("name":"%s", "number":"%")" PRId64);
        return 0;
    }
    

    Result:

    "name":"%s", "number":"%"ld
    

    Now you see the errors:

    • You have an extra " between % and ld.
    • " is missing after ld.

    Based on this, fix the format string:

    #include <cstdio>
    #include <cinttypes>
    
    int main(void) {
        std::int64_t num = INT64_MAX;
        std::printf(R"("name":"%s", "number":"%)" PRId64 R"(")", "david", num);
        return 0;
    }
    

    Result:

    "name":"david", "number":"9223372036854775807"