C ++中的字符串和int连接

时间:2016-08-29 03:52:34

标签: c++ string int concatenation stdstring

[["blank", "blank", "blank"],
["blank", "yellow", "green"],
["blank", "blue", "blank"]]

我期望结果为:

doc.FirstSection.Body.FirstParagraph.Runs.Add(new Run(doc, ControlChar.PageBreak));

在控制台中按照这样打印:

string words[5];
for (int i = 0; i < 5; ++i) {
    words[i] = "word" + i;
}

for (int i = 0; i < 5; ++i) {
    cout<<words[i]<<endl;
}

有人可以告诉我这个的原因。我相信在java中它会按预期打印。

3 个答案:

答案 0 :(得分:8)

C ++不是Java。

在C ++中,"word" + i是指针算术,它不是字符串连接。请注意,string literal "word"的类型为const char[5](包括空字符'\0'),然后在此处衰减为const char*。因此,对于"word" + 0,您将获得指向第一个字符(即const char*)的类型w的指针,对于"word" + 1,您将获得指针指针到第二个字符(即o),依此类推。

您可以将operator+std::stringstd::to_string(自C ++ 11)一起使用。

words[i] = "word" + std::to_string(i);

顺便说一句:如果你想要word1word5,你应该使用std::to_string(i + 1)代替std::to_string(i)

答案 1 :(得分:3)

 words[i] = "word" + to_string(i+1);

有关to_string()

的详细信息,请查看此link

答案 2 :(得分:1)

我更喜欢以下方式:

  string words[5];
  for (int i = 0; i < 5; ++i) 
  {
      stringstream ss;
      ss << "word" << i+1;
      words[i] = ss.str();
  }
相关问题