如何将单个字符转换为 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