Need Help With File Input.

I was trying the following exercise:

Create a Text class that contains a string object to hold the text of a file. Give it two constructors: a default 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.

Based on useful info provided by our fellow forumer.I came up with this code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include<iostream>
#include<string>
#include<fstream>
using namespace std;

class Text{
      string str;
      public:
             Text();
             Text(string);
             string contents();
             };
             
Text::Text()
{}

Text::Text(string s)
{
  ifstream in(s.c_str()); 
  string temp;
  while(getline(in,temp))
   str += temp+"\n";
}

string Text::contents()
{return str;}

int main()
{
    string newstr;
    cin>>newstr;
    Text txt(newstr);
    newstr= txt.contents();
    cout<<newstr<<endl;
    return 0;
}


But this is not working.
And What is the function c_str() called, how it works and any other info regarding this function if anyone could provide.

I tried with input:

"E:\CPP\try"
and
E:\CPP\try

but the program does not gives any output. There are no compiler or linker errors.

PS:Sorry for sounding like a complete noob(which I am) and annoying.
Any help is really appreciated.
Thank You for reading.
Regards.
It all seems to be working correctly for me, don't forget with the way it is currently set up you will need to include .txt at the end of whatever file you are trying to open.

The function c_str() just converts the string to a const char* variable. This is needed because that is the only thing fstream is able to work with.

http://www.cplusplus.com/reference/string/string/c_str/
James2250, Thank You very much sir for giving your precious time to this post and for sharing the valuable knowledge with me . Now it does works for me too.
Regards.
Topic archived. No new replies allowed.