Reading in a file and then displaying the contents

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 :)
Last edited on
1
2
3
4
5
6
Text::Text(string filename){
   std::ifstream in(filename); //if you have an old compiler and get an error, use filename.c_str()
   std::string line;
   while(std::getline(in, line))
      this->s += line +'\n';
}
That's awesome. thank you very much.

I'm not sure if point 1. is solved or not, but point 2. works as intended now.

In regards to point 1. I'm not if I should maybe use cassert() and check to see the filenames match and if not throw an error, but since I'm the one supplying the filename to the program I not sure if it matters that much.

Thank you for your help :)

well , you may check that the file does open an throw an exception
1
2
3
4
std::isftream in(filename);
if(not in){ //couln't open the file
   throw std::invalid_argument("cannot open " + filename);
}
Topic archived. No new replies allowed.