2012-10-16 6 views
0

가능한 복제를 문자열을 추가하고 값 int :
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; 
} 
+3

'std :: string'에 'int'를 추가 할 수있는 가능성은 http://stackoverflow.com/questions/10516196/append-an-int-to-a-stdstring/10516313#10516313 – hmjd

답변

3

해당 숫자만큼 포인터를 앞으로 이동시키는 문자 포인터에 정수를 추가합니다. 모든 종류의 전환을 수행하는 대신 std::stringstream을 사용하십시오. 이런 식으로 뭔가 :는 MWE이 stringstream를 사용

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

을 참조하십시오. 내 주된 권리로 쓰여졌 을까? 이것은 내가 toString 메소드에서 모든 것을 수행한다고 가정하는 숙제이며, 나의 주요 메소드에서 나는 그것을 호출하여 디스플레이 할 것이다. –

+0

ok thx가 테스트되었고 그 덕분에 D : D –

1

:

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

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

출력 "안녕 40bye"예상대로.

this question도 참조하십시오.