2016-07-05 121 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

不要嘗試從插入器內部沖洗。沒有一個標準插件能夠做到這一點。請在main的插入器電話後加上std::cout << '\n';

這裏的問題是std::cout是行緩衝的。這意味着它將插入的字符保存在內部緩衝區中,直到它看到一個換行符(或直到它被明確刷新)。如果插入std::string對象但不結束該行,則會看到相同的行爲。