如何將單個字元轉換為 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);
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP