2013-08-30 4 views
-1

intstringstringstream을 어떻게 할당합니까?stringstream에 int에 문자열을 어떻게 할당합니까?

은 "stringstream(mystr2) << b;"아래의 예 mystr2-b를 할당하지 않습니다

#include <iostream> 
#include <string> 
#include <sstream> 

using namespace std; 

int main() 
{ 
    string mystr = "1204"; 
    int a; 
    stringstream(mystr) >> a; 
    cout << a << endl; // prints 1204 

    int b = 10; 
    string mystr2; 
    stringstream(mystr2) << b; 
    cout << mystr2 << endl; // prints nothing 
    return 0; 
} 

답변

3

이 수행해야합니다

stringstream ss; 
ss << a; 
ss >> mystr; 

ss.clear(); 
ss << b; 
ss >> mystr2; 
+1

흠, 그는 아니, 첫 번째 부분과의 문제가 아니라했다? :) 'b'는 mystr2와 함께 거기에서 더 명확 해졌을 것입니다. – lpapp

0

이 올바르게 아래의 '10'을 출력한다.

#include <iostream> 
#include <string> 
#include <sstream> 

using namespace std; 

int main() 
{ 
    string mystr = "1204"; 
    int a; 
    stringstream(mystr) >> a; 
    cout << a << endl; // prints 1204 

    int b = 10; 
    string mystr2; 
    stringstream ss; 
    ss << b; 
    ss >> mystr2; 
    cout << mystr2 << endl; // prints 10 
    return 0; 
} 
1
int b = 10; 
string mystr2; 
stringstream ss; 
ss << b; 
cout << ss.str() << endl; // prints 10 
+0

"ss << << b"는 나에게 잘못 보입니다. – lpapp

+0

여유 공간이 남아 있습니다. ;-) – lpapp

+0

@ LaszloPapp, 미안 해요, 내가 복사했을 때, 나는 여분의'<<'을 청소하지 않았습니다. –

0

당신이 ctor에있는 문자열 스트림을 생성 은 stringstream(mystr2)mystr2 버퍼의 초기 내용으로 복사됩니다. mystr2은 스트림에 대한 후속 작업에 의해 수정되지 않습니다.

int b = 10; 
string mystr2; 
stringstream ss = stringstream(mystr2); 
ss << b; 
cout << mystr2.str() << endl; 

constructorstr 방법을 참조하십시오

스트림의 내용이 당신이 str 방법을 사용할 수 있습니다 얻으려면.

0

당신의 문자 질문에 대한 답변은 다음과 같습니다

int b = 10; 
std::string mystr2 = static_cast<stringstream &>(stringstream()<<b).str(); 
cout << mystr2 << endl; 
관련 문제