Last Updated on 2021-10-22 by Clay
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 ofstd:string
- Use
cout
instead ofprintf()
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