Hello all. I've been a lurker here and have searched the forums for the answer to my question, and while I've seen several topics regarding the same question I wasn't able to find an answer that worked for me. I apologize in advance to anyone that is tired of seeing this question, or ones similar to it.
Heads up, this is an assignment/homework question, but I'm not looking for anyone to write the code for me, I'm just stuck on two points (I think that's it.) My issues are:
1. The constructor will take any string argument not just the actual filename, which I can't figure out how to do properly.
2. The contents of "s" will display in the Text::Text(string s) function but not in the "void Contents()" where I actually need it to display from.
I appreciate any help that you can offer. Thanks :)
Write a program in which you 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
of the file into the string member object. Add a member function
contents() to return the string so that you can display it. In
main(), open a file using Text and display the contents.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
Text::Text(string s) // not taking the file name, just using any string in the argument to open the file
{
ifstream in("File.txt");
while(getline(in, s))
cout << s << "\n"; // contents of s are displayed from here, but not in Contents which is where I need it to actually output from
}
void Text::Contents()
{
// return s; // doesn't return anything
cout << s << "Inside Contents\n"; // Not displaying anything for 's'
}
int main()
{
Text t("log.txt");
t.Contents();
}
|
edited to remove the full code and left the relevant parts that ne555 provided the very helpful solution for. Thank you ne555 :)