简体   繁体   English

c ++附加到字符串

[英]c++ appending to string

Is there an easy way to append an integer to a string?有没有一种简单的方法可以将整数附加到字符串?

I have a for loop like this:我有一个这样的 for 循环:

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

and I need to get the index of the array which is equal, and the index of course is an integer type.并且我需要获取相等的数组的索引,并且索引当然是整数类型。 But as I do this I get an error:但是当我这样做时,我收到一个错误:

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

is there a way to fix this?有没有办法来解决这个问题?

Use stringstream if you are working with std::strings: #include <sstream>如果您使用 std::strings,请使用 stringstream: #include <sstream>

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

newString will be "old5" newString"old5"

Yes .是的

You can, for example:例如,您可以:

  • use the itoa function that converts integers into strings使用itoa函数将整数转换为字符串
  • make your kodas an ostringstream and "write" into it as you would to cout : kodas << g让你的kodas一个ostringstream和“写”进去,你会到coutkodas << g

The easiest is like so:最简单的就是这样:

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

If you don't have C++11, use boost::lexical_cast<std::string>(g) instead.如果您没有 C++11,请改用boost::lexical_cast<std::string>(g)

Failing everything, you can do something terrible like this:一切都失败了,你可以做这样可怕的事情:

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

itoa(), its the into to alpha function, should help you out. itoa(),它的 into alpha 函数,应该可以帮助你。 sprintf or vsprintf works too if you want to如果您愿意,sprintf 或 vsprintf 也可以使用

There are several ways of formatting a number as a string in C++, including sprintf() , boost:lexical_cast() , and others.在 C++ 中有几种将数字格式化为字符串的方法,包括sprintf()boost:lexical_cast()等。 See The String Formatters of Manor Farm for a good comparison and additional suggestions.请参阅Manor Farm 的字符串格式化程序以获得良好的比较和其他建议。 In addition, C++11 has std::to_string .此外,C++11 有std::to_string Your compiler may or may not have it yet.您的编译器可能还没有。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM