2012-11-20 198 views
0

是否有一种简单的方法来将整数附加到字符串?C++追加到字符串

我有一个像这样循环:

for(int i=0;i<text.length();i++){ 
     for(int g=0;g<word.length();g++){ 
      if(text[i]==word[g]){ 
       kodas.append(g); 
      } 
     } 
    } 

和我需要得到其等于阵列的索引,和当然的索引是整数类型。但是,当我这样做,我得到一个错误:

invalid conversion from ‘int’ to ‘const char*’ [-fpermissive]| 

有没有办法解决这个问题?

+1

这会实现什么?你最终会得到一个无意义的十进制数字连接... –

+1

将一个整数附加到一个字符串是没有用的,就像将一个乘客附加到列车上一样。你想要的是将整数写入一个字符串的末尾。这表明你宁愿使用'stringstream'而不是'string'。 – leftaroundabout

回答

6

使用stringstream的,如果你用的std ::字符串:#include <sstream>

#include <sstream> 
using namespace std; 
string oldString = "old"; 
int toAppend = 5; 
stringstream ss(toAppend); 
string newString = oldString + ss.str(); 

newString"old5"

+2

我推荐'stringstream ss(oldString);'然后只是'ss.str()'是结果。 –

1

可以,例如:

  • 使用itoa函数转换整数为字符串
  • 让你kodasostringstream和 “写” 进去,你会到coutkodas << g
1

最简单的就是这样:

if (kodas.empty()) { kodas += ' '; } 
kodas += std::to_string(g); 

如果您没有C++ 11,请改为使用boost::lexical_cast<std::string>(g)

失败的一切,你可以做什么可怕的事情是这样的:

kodas += static_cast<std::ostringstream&>(std::ostringstream() << g).str(); 
+0

我喜欢这个static_cast技巧!为什么它不好? – d33tah

+1

@ d33tah:这不坏,它看起来很可怕。 –

0

itoa(),其进入到阿尔法功能,应该可以帮助你。 sprintf的或vsprintf中工作过,如果你想

+2

建议'vsprintf'而不是'vsnprintf'是边缘犯罪!你是僵尸网络吗? –