【问题标题】:How can I combine a string and a string size in a function in C++? [closed]如何在 C++ 中的函数中组合字符串和字符串大小? [关闭]
【发布时间】:2017-10-13 18:11:06
【问题描述】:

我昨天刚开始学习 C++,我有 Java 的基本知识,并且正在尝试基础知识。我正在尝试制作一个非常基本的程序来理解这种语言的语法。

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

int main() 
{
    string bacon = "How many characters are in the following? ";
    string chedder = "icecream";
    string cheSize = chedder.size();
    string snow = bacon + " " + "\"" + chedder + "\"" + "The number is : " + cheSize;

    cout << snow;
    return 0;
}

我做错了什么?

另外,我注意到 cout 不能组合多个字符串,例如

cout << snow + chedder; 

没用。

这是什么原因?感谢您的宝贵时间!

【问题讨论】:

  • string cheSize = chedder.size(); size 返回 int 而不是 string。
  • 在使用东西之前先reading the famous manual怎么样?
  • 你不能通过做一些随机的事情并询问stackoverflow为什么它不起作用来学习C++。

标签: c++ string operator-overloading


【解决方案1】:

表达式

chedder.size()

具有整数类型std::string::size_type。类std::string 中没有可以将整数隐式转换为std::string 类型的对象的转换构造函数。

所以这个说法

string cheSize = chedder.size();

错了。

因此,std::string 类型的对象和整数没有重载的operator +。相反,您应该使用标准函数std::to_string 将整数转换为字符串并应用operator +

所以改用下面的代码

string bacon = "How many characters are in the following? ";
string chedder = "icecream";
string::size_type cheSize = chedder.size();
string snow = bacon + " " + "\"" + chedder + "\"" + "The number is : " + to_string( cheSize );

cout << snow << endl;

还有这句话

cout << snow + chedder;

如果两个变量都具有 std::string 类型或其中一个具有 std::string 类型而另一个具有字符数组类型或指向 char 的指针,则正确。

【讨论】:

    【解决方案2】:

    size() 返回一个整数类型(具体来说是std::string::size_type),而不是string。并且与其他一些语言不同的是,当您分配给字符串变量时,C++ 不会自动将整数转换为 string

    如果您使用的是 C++11 或更高版本,则可以使用 to_string() 方法对其进行转换。

    string cheSize = chedder.size().to_string();
    

    【讨论】:

    【解决方案3】:

    你可能想要:

    cout << snow << " " << chedder;
    

    还要注意,chedder.size(); 返回的是一个整数,而不是字符串。

    【讨论】:

      【解决方案4】:

      您不能将整数值分配给字符串对象。

      std::string cheSize = chedder.size(); // error
      

      如果你愿意,你可以使用std::to_string:

      std::string cheSize = std::to_string(chedder.size());
      

      【讨论】:

        猜你喜欢
        • 2023-03-07
        • 2014-04-24
        • 1970-01-01
        • 2014-11-01
        • 2021-10-12
        • 1970-01-01
        • 2012-07-16
        • 2017-01-14
        • 1970-01-01
        相关资源
        最近更新 更多