2011-03-04 6 views
20

다음과 같은 cout 문이 있습니다. 가변 인수 목록을 변환하고 Msg에 저장하려면 vsnprintf으로 전달해야하므로 char 배열을 사용합니다.std :: string에 cout 출력을 내 보냅니다.

cout을 C++ std::string에 출력 할 수있는 방법이 있습니까?

char Msg[100]; 
char appname1[100]; 
char appname2[100]; 
char appname3[100]; 

// I have some logic in function which some string is assigned to Msg. 
std::cout << Msg << " "<< appname1 <<":"<< appname2 << ":" << appname3 << " " << "!" << getpid() <<" " << "~" << pthread_self() << endl; 

답변

44

당신은 stringstream에 의해 cout을 대체 할 수 있습니다.

std::stringstream buffer; 
buffer << "Text" << std::endl; 

buffer.str()을 사용하여 문자열에 액세스 할 수 있습니다. 대신 cout을의 다음 코드를 변경 ostringstream (또는 이제 stringstream)를 사용할 수있는 경우

+0

내가 그렇게 어떻게, cout을에서 mutilple 문자열을 가지고있다. thanks – venkysmarty

+1

@venkysmarty : 각 문자열 다음에 버퍼를 지울 수 있습니다. 문자열이 공백 또는 이와 유사한 것으로 분리되어 있으면 분리 할 수 ​​있습니다. –

+0

이것을 printf와 함께 사용하려면 어떻게해야합니까? 분명히 나는 ​​cout과 달리 버퍼로 printf를 대체 할 수 없다! – Breeze

2

를 사용할 수 있습니다.

코드를 변경할 수없고 출력중인 내용을 "캡처"하려는 경우 출력을 리디렉션하거나 파이프 할 수 있습니다.

그러면 프로세스가 공유 메모리를 통해 파일을 읽거나 파이프 된 정보를 가져올 수 있습니다.

0
#include <stdio.h> 

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

// This way we won't have to say std::ostringstream or std::cout or std::string... 
using namespace std; 

/** Simulates system specific method getpid()... */ 
int faux_getpid(){ 
    return 1234; 
} 

/** Simulates system specific method pthread_self()... */ 
int faux_pthread_self(){ 
    return 1111; 
} 

int main(int argc, char** argv){ 

    // Create a char[] array of 100 characters... 
    // this is the old-fashioned "C" way of storing a "string" 
    // of characters.. 
    char Msg[100]; 


    // Try using C++-style std::string rather than char[], 
    // which can be overrun, leading to 
    // a segmentation fault. 
    string s_appname1; 

    // Create old-fashioned char[] array of 100 characters... 
    char appname2[100]; 

    // Create old-fashioned char[] array of 100 characters... 
    char appname3[100]; 

    // Old-fashioned "C" way of copying "Hello" into Msg[] char buffer... 
    strcpy(Msg, "Hello"); 

    // C++ way of setting std::string s_appname equal to "Moe"... 
    s_appname1 = "Moe"; 

    // Old-fashioned "C" way of copying "Larry" into appname2[] char buffer... 
    strcpy(appname2, "Larry"); 

    // Old-fashioned "C" way of copying "Shemp" into appname3[] char buffer... 
    strcpy(appname3, "Shemp"); 

    // Declare le_msg to be a std::ostringstream... 
    // this allows you to use the C++ "put-to" operator << 
    // but it will "put-to" the string-stream rather than 
    // to the terminal or to a file... 
    ostringstream le_msg; 

    // Use put-to operator << to "write" Msg, s_appname1, s_appname2, etc... 
    // to the ostringstream...not to the terminal... 
    le_msg << Msg << " "<< s_appname1 <<":"<< appname2 << ":" << appname3 << " " << "!" << faux_getpid() <<" " << "~" << faux_pthread_self(); 

    // Print the contents of le_msg to the terminal -- std::cout -- 
    // using the put-to operator << and using le_msg.str(), 
    // which returns a std::string. 
    cout << "ONE: le_msg = \"" << le_msg.str() << "\"..." << endl; 

    // Change contents of appname3 char[] buffer to "Curly"... 
    strcpy(appname3, "Curly"); 

    // Clear the contents of std::ostringstream le_msg 
    // -- by setting it equal to "" -- so you can re-use it. 
    le_msg.str(""); 

    // Use put-to operator << to "write" Msg, s_appname1, s_appname2, etc... 
    // to the newly cleared ostringstream...not to the terminal... 
    // but this time appname3 has been set equal to "Curly"... 
    le_msg << Msg << " "<< s_appname1 <<":"<< appname2 << ":" << appname3 << " " << "!" << faux_getpid() <<" " << "~" << faux_pthread_self(); 

    // Print the new contents of le_msg to the terminal using the 
    // put-to operator << and using le_msg.str(), 
    // which returns a std::string. 
    cout << "TWO: le_msg = \"" << le_msg.str() << "\"..." << endl; 

    // This time, rather than using put-to operator << to "write" 
    // to std::ostringstream le_msg, we'll explicitly set it equal 
    // to "That's all Folks!" 
    le_msg.str("That's all Folks!"); 

    // Print the new contents of le_msg "That's all Folks!" to 
    // the terminal via le_msg.str() 
    cout << "THREE: le_msg = \"" << le_msg.str() << "\"..." << endl; 

    // Exit main() with system exit value of zero (0), indicating 
    // success... 
    return 0; 

}/* main() */ 

출력 :

ONE: le_msg = "Hello Moe:Larry:Shemp !1234 ~1111"... 
TWO: le_msg = "Hello Moe:Larry:Curly !1234 ~1111"... 
THREE: le_msg = "That's all, folks!"... 
+1

Answer – depperm

+0

위 코드의 @depperm에 주석을 추가 했으니 이제는 조금 더 이해할 수있을 것입니다. [std :: ostringstream의 공식 문서] (http://www.cplusplus.com/reference/sstream/ostringstream/)도 참고하십시오. –

관련 문제