jeudi 24 septembre 2015

Overloading >> to work with string objects

This is part of my header file.

#ifndef MY_STRING_H
#define MY_STRING_H

#include <iostream>


using namespace std;

class MyString
{
public:

MyString();
MyString(const char[]);
MyString(const MyString&);
~MyString();

private:
char *      pChar;
size_t      NumChars;
size_t      NumSlots;

friend istream &operator >>(istream &,  MyString &);
};

inline istream& operator >>(istream &in,  MyString & Str)
{
in >> Str.pChar;
in >> Str.NumChars;
in >> Str.NumSlots;
return in;
}

In my main.cpp im trying to

cout << "Enter a string: ";
cin >> Str6;

The problems I'm having is, I cant seem to figure out a way to allocate enough space for the new string that is being entered and it also seems to only take the characters up to the first space. so output is like this:

Enter a String: does it work?
You String is: does

then i get a wrote to memory after end of heap buffer error pop up. I was thinking I could use some code from my copy constructor to temporarily build a new Str obj with enough space but I have no idea how to get the character count to make it big enough. Am I on the right track here?

Aucun commentaire:

Enregistrer un commentaire