【问题标题】:Why is this c++ string concatenation missing a space?为什么这个 c++ 字符串连接缺少空格?
【发布时间】:2010-05-31 02:44:52
【问题描述】:

我正在使用 c++ 字符串,并且是编程的初学者。

我期待:99 个红气球

但我收到:99 个红气球

这是为什么呢?

#include <string>
#include <iostream>
using namespace std;

int main()
{
    string text = "9";
    string term( "9 ");
    string info = "Toys";
    string color;
    char hue[4] = {'R','e','d','\0'};
    color = hue;
    info = "Balloons";
    text += (term + color + info);
    cout << endl << text << endl;
    return 0;
}

【问题讨论】:

    标签: c++ string io


    【解决方案1】:

    您对hue 的定义不包含任何空格。 (\0 是 C++ 知道字符串结尾在哪里的方式,这不是空格。)请注意,您的代码中的 term 确实有一个尾随空格。

    要修复它,请将色调更改为:

    char hue[5] = {'R','e','d',' ','\0'};
    

    或者,在构建最终文本时,在添加中包含一个空格:

    text += (term + color + " " + info);
    

    【讨论】:

      【解决方案2】:

      这是因为字符串只是逐个字符连接,并且 info = "Balloons" 或颜色中没有空格。请注意,“\0”不是空格。 要获得您需要的空间:

       text += (term + color + " " + info);
      

      【讨论】:

        【解决方案3】:

        因为在 colr 的末尾或 info 的开头都没有空格。所以你可以试试:

         info = " Balloons";
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-08-15
          • 2019-07-22
          • 2017-03-11
          • 2014-11-23
          • 1970-01-01
          相关资源
          最近更新 更多