2012-11-20 199 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'是邊緣犯罪!你是僵屍網絡嗎? –