【问题标题】:adding a string and int to a string [duplicate]将字符串和int添加到字符串[重复]
【发布时间】:2012-10-06 11:42:27
【问题描述】:

可能重复:
Append an int to a std::string

我想将字符串和 int 添加到我的字符串中。

在我的 LocationData::toString() 方法中,我试图将一堆东西一起添加到我的字符串 str 中。

它添加了第一个输入,它是一个字符串 sunType,它添加了第二个输入,一个整数。 编译没有问题,但是当我运行我的代码时,输​​出是

太阳类型:sunNo 类地行星:

应该是这样的

太阳类型:

没有类似地球的行星:

所以我的代码有问题吗? 我没有显示我的整个代码,因为它有些冗长。希望有人能回答我谢谢!

#include <iostream>
#include <string>

using namespace std;

class LocationData
{   
    private:
    string sunType;
    int noOfEarthLikePlanets;
    int noOfEarthLikeMoons;
    float aveParticulateDensity;
    float avePlasmaDensity;
    public:
    string toString();

};

string LocationData::toString()
{
    string str = "Sun Type: " + getSunType();
    str += "\nNo Of Earth Like Planets: " + getNoOfEarthLikePlanets();
    //str += "\nNo Of Earth Like Moons: " + getNoOfEarthLikeMoons();
    //str += "\nAve Particulate Density: " + getAveParticulateDensity();
    //str += "\nAve Plasma Density: " + getAvePlasmaDensity();
    return str;
}

int main()
{

    cout<<test.toString()<<endl;
}

【问题讨论】:

标签: c++ string int


【解决方案1】:

您正在向字符指针添加一个整数,该整数使指针前进所述数字。使用std::stringstream 来执行此操作,而不是进行各种转换。像这样的:

std::stringstream ss;
ss << "Sun Type: " << getSunType() << "\nNo Of Earth Like Planets: "<<getNoOfEarthLikePlanets();
std::string s = ss.str();

【讨论】:

  • er 这应该写在我的主要权利?这是学校的作业,我想在我的 toString 方法中完成所有这些,在我的主要方法中,我将调用它并根据
  • ok thx 测试和它的工作感谢:D
【解决方案2】:

一个使用stringstream的MWE:

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

int main(){
    stringstream ss;
    int i=40;
    ss<<"Hi ";
    ss<<i;
    ss<<"bye";
    cout<<ss.str()<<endl;
}

按预期输出“Hi 40bye”。

另见this question。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-28
    相关资源
    最近更新 更多