Reputation: 9
For a class assignment I have to overload the insertion and extraction operators. I'm having trouble getting it to print to the console.
EDITED
Sorry, this is my first time posting. I realize that I didn't post enough info for you guys, I have updated with what should be the necessary code
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;
}
Upvotes: 0
Views: 651
Reputation: 76370
Don't try to flush from inside an inserter. None of the standard inserters does that. Just add std::cout << '\n';
after the call to your inserter in main
.
The issue here is that std::cout
is line buffered. That means it saves the inserted characters in an internal buffer until it sees a newline character (or until it's explicitly flushed). You'll see the same behavior if you insert a std::string
object but don't end the line.
Upvotes: 1
Reputation: 1775
use the ostream::flush()
method. As in:
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;
}
Upvotes: 1