1. 程式人生 > >C語言printf輸出string型別字串

C語言printf輸出string型別字串

知識點:

1.printf函式輸出字串是針對char *的,即printf只能輸出c語言的內建資料,而string不是c語言的內建資料。

2.string型別的物件不止包含字串,還包含了許多用於操作函式,所以&str並非字串的首地址。

3.如需輸出string物件中的字串,可以使用string的成員函式c_str(),該函式返回字串的首字元的地址。

錯誤示例:

#include<stdio.h>
#include<string.h>

int main(){
	string str="hello";
	printf("%s",str);

    return 0;
}

編譯報錯:

 [Error] cannot pass objects of non-trivially-copyable type 'std::string {aka class std::basic_string<char>}' through '...'

正確示例:

#include<stdio.h>
#include<string.h>

int main(){
	string str="hello";
	printf("%s",str.c_str());    // 呼叫c_str()函式

    return 0;
}

執行結果:

 

 

 

 

參考自:https://blog.csdn.net/cjolj/article/details/55267660