Skip to content

[Solved][C++] cannot pass non-trivial object of type ‘std::__1::string’ (aka ‘basic_string<char, char_traits, allocator >’) to variadic function; expected type from format string was ‘char *’

Problem

If you want to print a string data type variable in C programming language, you can use the following code:

#include <stdio.h>

int main() {
    char s[] = "Today is a nice day.";
    printf("%s\n", s);
    return 0;
}


Output:

Today is a nice day.



But if you use these code in C++ language, it does not work.

#include <string>


int main() {
    std::string s = "Today is a nice day";
    printf("%s\n", s);
    
    return 0;
}


You will see the following error message:

error: cannot pass non-trivial object of type 'std::string' (aka
      'basic_string<char, char_traits<char>, allocator<char> >') to variadic
      function; expected type from format string was 'char *'
      [-Wnon-pod-varargs]
    printf("%s\n", s);
            ~~     ^
test.cpp:6:20: note: did you mean to call the c_str() method?
    printf("%s\n", s);
                   ^
                    .c_str()
1 error generated.


這個問題發生的原因其實很簡單:printf() 只支援 C 樣式的字串C-style String),並不支援如 std::string 的資料型態。

The reason of this problem is very obvious: printf() function just expect type from format ‘char *‘; It does not support the std:string data type.


Solution

There are three solutions:

  • Use char s[] to declare your string variable.
  • Use c_str() instead of std:string
  • Use cout instead of printf()

The usage method of c_str() is yourString.c_str():

#include <string>


int main() {
    std::string s = "Today is a nice day";
    printf("%s\n", s.c_str());
    
    return 0;
}


Output:

Today is a nice day

References


Read More

Leave a Reply