C++ printf with std::string

在c++里面使用printf輸出std::string字符串會(huì)出現(xià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,也就是說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.

至于為什么這種方法是不推薦的,參見:
https://stackoverflow.com/questions/10865957/c-printf-with-stdstring

補(bǔ)充:

同理,輸入字符串到std::string的時(shí)候,不能用scanf("%s", &s);,而應(yīng)該用std::cin >> s;

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容