Hi there
I am trying to pass in a text file into a constructor in my Text class.
I am confused when using the .c_str function
If I am trying to pass a text file (e.g file.txt) is it correct to use:
ifsream ifs(file.c_str());
?
can someone help explain how the c_str() works in this case, I am not finding much help online.
1 2 3 4 5 6 7 8 9
class Text { //declaring the string class
string text; //creates a string object to hold the text of a file
public:
Text() {} //constructor 1
Text(const string& fname) { //overloaded constructor
ifstream ifs(file.txt.c_str());
string line;
while (getline(ifs, line))
text += line + '\n';
in simple terms, c_str() gives you a c-style string representation of a c++ string. you use it when you need to pass a c++ string to a function that expects a c style string.
In your code , Replace: ifstream ifs(file.txt.c_str());
with: ifstream ifs(fname.c_str());
that is because, string fname holds whatever file name you will pass e.g file.txt