【问题标题】:How to push_back an integer to a string?如何 push_back 一个整数到一个字符串?
【发布时间】: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


【解决方案1】:

push_back单个字符附加到字符串。你想要的是 convert 一个数字 to 一个字符串,然后将这个字符串连接到另一个字符串。这是完全不同的操作。

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

std::string prefix = std::string(1, C++);
L.push_back(prefix + std::to_string(i));

如果你的编译器还不支持 C++11,可以使用stringstream

std::ostringstream ostr;
ostr << C++ << i;
L.push_back(ostr.str());

【讨论】:

  • 这种情况下不需要peas,直接将ostr.str()推回L即可。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-18
相关资源
最近更新 更多