2016-07-05 6 views
0

클래스를 지정하려면 삽입 및 추출 연산자를 오버로드해야합니다. 콘솔로 인쇄하는 데 문제가 있습니다.C++ flush()가 작동하지 않습니까? endl을 사용할 수 없습니다

이 내 처음으로 게시

미안 편집. 내가 너희들을위한 충분한 정보를 게시하지 않았다 실현, 나는 필요한 코드

driver.cpp

#include "mystring.h" 
#include <iostream> 

using namespace std; 

int main(){ 
    char c[6] = {'H', 'E', 'L', 'L', 'O'} 
    MyString m(c); 
    cout << m; 

    return 0; 
} 

mystring.h을해야 무엇으로 업데이트 한

class MyString 
{ 
    friend ostream& operator<<(ostream&, const MyString&); 

    public: 
    MyString(const char*); 
    ~MyString(const MyString&) 

    private: 
    char * str; //pointer to dynamic array of characters 
    int length; //Size of the string 

    }; 

의 mystring.cpp

#include "mystring.h" 
#include <iostream> 
#include <cstring> 

using namespace std; 

MyString::MyString(const char* passedIn){ 
    length = strlen(passedIn)-1; 
    str = new char[length+1]; 
    strcpy(str, passedIn); 
} 

MyString::~MyString(){ 
    if(str != NULL){ 
    delete [] str; 
    } 
} 

ostream& operator << (ostream& o, const MyString& m){ 
    for(int i = 0; i < strlen(m.str); i++){ 
    o << m.str[i]; 
    } 
    o.flush(); 
    return o; 
} 
+5

관련 'MyString' 코드를 게시하거나'MyString'이 필요하지 않은 [mcve]를 만드는 것이 좋습니다. – juanchopanza

+4

널 문자가 누락되어 있기 때문에 기분이 나아졌습니다. –

+1

또한 m.str이 C 스타일 문자열이면이 코드는 마지막 문자를 버립니다. 표시된 코드에 여러 문제가 있습니다. –

답변

1

ostream::flush() 방법을 사용합니다. 다음과 같이 :

ostream& operator << (ostream& o, const MyString& m){ 
    for(int i = 0; i < strlen(m.str)-1; i++){ 
     o << m.str[i]; 
    } 
    o.flush(); 
    return o; 
} 
+1

미래의 독자들에게 이것이 조작자 ['std :: flush'] (http://en.cppreference.com/w/cpp/io/manip/flush)를 사용하는 것과 어떻게 다른지에 대한 답을 추가하는 것이 유익합니다. OP가하고있는 것처럼 그러한 차이가 없다면, 아마도 이것은 문제가 아닙니다. – WhozCraig

+0

나는 flush를 멤버 함수로 사용해도 동일한 결과를 얻으려고했다. 더 많은 유용한 정보를 포함하려고 내 게시물을 업데이트했습니다. –

1

삽입 기 내부에서 플러시하지 마십시오. 표준 삽입 기가 없습니다. 삽입 기 호출 후 mainstd::cout << '\n';을 추가하십시오.

여기서 문제는 std::cout이 줄 바꿈 됨입니다. 즉, 개행 문자가 보일 때까지 (또는 명시 적으로 플러시 될 때까지) 삽입 된 문자를 내부 버퍼에 저장합니다. std::string 개체를 삽입했지만 줄을 끝내지 않으면 동일한 동작을 볼 수 있습니다.