【发布时间】:2013-10-13 06:33:00
【问题描述】:
现在,我正准备做一个家庭作业,首先整理一下我将在我的方法中要做的事情。对于其中一个,我必须准备一个名称列表,以 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
}
字母字符可以很好地添加和递增值(它们显示为 ABC 等),但我遇到的问题是,当我 push_back 整数值时,它实际上并没有 push_back 整数值,但是与整数相关的 ascii 值(这是我的猜测——它返回表情符号)。
我认为这里的解决方案是将整数值转换为字符,但是到目前为止,查找它一直很混乱。我尝试过 to_string (给我错误)和 char(i) (与 i 相同的结果)但没有一个有效。所以基本上:我怎样才能将 i 添加为代表它所拥有的实际整数的 char 值而不是 ascii 值?
我的助教通常不会真正阅读发送给他的代码,而且讲师需要很长时间才能回复,所以我希望我能在这里解决这个问题。
谢谢!
【问题讨论】:
-
如果
i永远不会大于9,您可以使用('0' + i) -
to_string应该可以工作,问题是为什么它在您的情况下不起作用。你得到了什么错误,你究竟为这种情况尝试了什么? -
您有为此使用
push_back? -
@DanielFrey 我得到“多个重载函数的实例与参数列表匹配”
-
peas.push_back(C++); peas.append(std::to_string(i))似乎会做你想做的事,并处理通过J的插入。
标签: c++ string char int push-back