如何將單個字元轉換為 C++ 中的字串?


有多種方法可以將單個字元轉換為字串。在以下示例中,其中一些方法用於將字元轉換為字串。

以下是 C++ 語言中將單個字元轉換為字串的示例,

示例

 即時演示

#include <iostream>
#include<string>
#include<sstream>

int main() {
   char c = 'm';

   std::string s(1, c);
   std::cout << "Using string constructor : " << s << '\n';

   std::string s2;
   std::stringstream s1;
   s1 << c;
   s1 >> s;
   std::cout << "Using string stream : " << s << '\n';

   s2.push_back(c);
   std::cout << "Using string push_back : " << s2 << std::endl;

   return 0;
}

輸出

以下是輸出

Using string constructor : m
Using string stream : m
Using string push_back : m

在以上程式中,使用了三種方法來將字元轉換為字串。首先,使用字串建構函式

std::string s(1, c);

其次,使用字串流

std::string s2;
std::stringstream s1;
s1 << c;
s1 >> s;

第三,使用字串 push_back

s2.push_back(c);

更新於: 25-6 月-2020

195 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.