如何在C ++中将char转换为字符串?

时间:2012-02-19 05:40:13

标签: c++

我有一个字符串变量s,我有一个地图数据结构(带字符串键)m

我想检查sm中的每个字母是否都存在,{I} m.containsKey(s[i])

因为,map containsKey函数需要字符串参数,我得到以下错误:

invalid conversion from char to const char* 

关于如何将char转换为字符串数据类型的任何想法?

5 个答案:

答案 0 :(得分:5)

取子串而不是索引。

s.substr(i, 1)

答案 1 :(得分:3)

另一种方法是:

#include <sstream>
#include <string>
stringstream ss;
string s;
char c = 'a';
ss << c;
ss >> s;

答案 2 :(得分:3)

string s="";
char a;

s+=a;

s is now a string of char a

答案 3 :(得分:0)

你可以做s.substr(i, 1)。但如果您的地图中只有char s,我更喜欢上面的答案。

答案 4 :(得分:0)

string str = "test";
anyFunction(str[x]);

[]运算符为您提供了一个char,如果任何函数需要字符串,那么肯定会发生错误。但你总是可以尝试这种偷偷摸摸的转换:

string str = "test";
char c = str[x];
string temp = c;
anyFunction(temp);