如何将整数push_back转换为字符串?

ass*_*tor 1 c++ string int char push-back

现在,我正准备做一个家庭作业,首先要弄清楚我将在我的方法中做些什么.对于其中一个,我必须准备一个名称列表,以便添加到A1,B2,C3等形式的列表中.我现在正在测试的是通过for循环添加它们的方法.请注意,我还没有完成所有事情,我只是确保项目以正确的形式制作.我有以下代码:

list<string> L; //the list to hold the data in the form A1, B2, etc.
char C = 'A'; //the char value to hold the alphabetical letters
for(int i = 1; i <= 5; i++)
{ 
    string peas; //a string to hold the values, they will be pushed backed here
    peas.push_back(C++); //adds an alphabetical letter to the temp string, incrementing on every loop
    peas.push_back(i); //is supposed to add the number that i represents to the temp string
    L.push_back(peas); //the temp string is added to the list
}
Run Code Online (Sandbox Code Playgroud)

字母字符添加并递增到值就好了(它们显示为ABC等),但我遇到的问题是当我push_back整数值时,它实际上并不是push_back整数值,而是ascii值与整数相关(这是我的猜测 - 它返回表情符号).

我认为这里的解决方案是将整数值转换为char,但是,到目前为止,查找它一直非常令人困惑.我试过to_string(给我错误)和char(i)(和我一样的结果),但没有一个有效.所以基本上:我如何将i添加为char值,表示它保存的实际整数而不是ascii值?

我的TA通常实际上并没有读取发送给他的代码,而且教师花了太长时间才回复,所以我希望我能在这里解决这个问题.

谢谢!

Kon*_*lph 5

push_back单个字符附加到字符串.你想要的是一个数字转换一个字符串,然后将该字符串连接到另一个字符串.这是一个根本不同的操作.

要将数字转换为字符串,请使用to_string.要连接字符串,您可以简单地使用+:

std::string prefix = std::string(1, C++);
L.push_back(prefix + std::to_string(i));
Run Code Online (Sandbox Code Playgroud)

如果你的编译器还不支持C++ 11,那么使用的解决方案是stringstream:

std::ostringstream ostr;
ostr << C++ << i;
L.push_back(ostr.str());
Run Code Online (Sandbox Code Playgroud)