2016-07-05 127 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对象但不结束该行,则会看到相同的行为。