The exercise says:
Create a Text class that contains a string object to hold the text of
a file. Give it two constructors: a default constructor and a
constructor that takes a string argument that is the name of the file
to open. When the second constructor is used, open the file and read
the contents into the string member object. Add a member function
contents() to return the string so (for example) it can be printed. In
main( ), open a file using Text and print the contents.
This is the class that I wrote:
class Text {
string fcontent;
public:
Text();
Text(string fname);
~Text();
string contents();
};
I haven’t understood everything of this exercise. It asks to create a function contents(), that returns a string, but it doesn’t says what the function has to do…
Neither what the default constructor has to do.
Could someone help me?
The function has to return the contents of the file, which is stored (in your case) in fcontents.
The default constructor doesn’t have to do anything in this case.
EDIT:
Seeing how many comments there are below with new problems, I’m going to recap and answer the rest of the questions here.
in Text.h you have:
and Text.cpp has
Point 1: The header file
<string>contains the class definition for std::string, the C++ string. This should not be confused with<cstring>which contains functions for manipulating C strings (const char *,const char[], etc).Point 2: The string class exists in the ::std namespace, which means we have to either use
std::stringevery time we want that class or useusing namespace std;to pull this class into the global scope. In the header file we prefer the former method because the using declaration doesn’t go away, which means that the namespace will be changed for every header and source file that includes this one, which we want to avoid in general (ie. always). In the cpp file however, there is no problem using the using declaration and we do so.Point 3: fstreams take a C string as the filename parameter, we can get the corresponding C string from a C++ string with the call
c_str(). This returns aconst char *.Point 4: To read the whole text file into a string is less obvious than it seems because the way streams deal with eof (end-of-file) and state-checking stuff. In short it will read one more time than you want it to (I know, wanting is subjective, but is close enough I think) before setting the eof flag. That’s why the state is checked after calling get and before adding what’s been read to our stringstream. Streams are a fairly elaborate topic so I won’t go into it in more detail here.
Point 5: Destructors on objects (non-pointers, like our fcontents is) are called automatically, so we don’t need to do anything to make sure that our fcontents string is destroyed when our Text object is destroyed. When we allocate something dynamically with
newthat’s when we have to worry about callingdeleteon it when we want to destroy it.