在c++里面使用printf
輸出std::string
字符串會(huì)出現(xiàn)一些問(wèn)題凹炸,如下:
#include<bits/stdc++.h>
int main ()
{
std::string s ("This is an sentence.");
std::cout << s << std::endl;
printf("%s\n", s);
return 0;
}
output:
This is an sentence.
?
printf
的結(jié)果是一個(gè)奇怪的字符,這是為什么呢陪竿?
這是因?yàn)?code>printf的"%s"
對(duì)應(yīng)的是C-style string,不支持std::string
休偶,也就是說(shuō)printf
不是類型安全的(isn't type safe)芭挽。正確的做法是使用std::cout << s << std::endl;
。
而如果非要使用printf
困乒,有一個(gè)不是很推薦的做法寂屏,使用std::string.c_str()
獲得const char *
的字符串,然后再輸出娜搂。
#include<bits/stdc++.h>
int main ()
{
std::string s ("This is an sentence.");
std::cout << s << std::endl;
printf("%s\n", s.c_str());
return 0;
}
output:
This is an sentence.
This is an sentence.
至于為什么這種方法是不推薦的迁霎,參見(jiàn):
https://stackoverflow.com/questions/10865957/c-printf-with-stdstring
補(bǔ)充:
同理,輸入字符串到
std::string
的時(shí)候百宇,不能用scanf("%s", &s);
考廉,而應(yīng)該用std::cin >> s;