reading from a file w/ .c_str



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';
Last edited on
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
Last edited on
so do I need to define the fname string before hand?
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

class Text { //declaring the Text class
string text; //creates a string object to hold the text of a file
string fname = "file.txt";

public:
Text() {}
Text(const string& fname) {
ifstream ifs(fname.c_str());
string line;
while (getline(ifs, line))
text += line + '\n';
}
string contents() {
return text;
}
};

int main(int argc, char* argv[]) {
if (argc > 1)
{
Text t1;
Text t2(argv[1]);
cout << "t1 :\n" << t1.contents() << endl;
cout << "t2 :\n" << t2.contents() << endl;
}
}

I am compiling ok, but I am not getting any output
Don't declare the variable filename inside your class, pass it as an argument to your constructor...
Last edited on
Topic archived. No new replies allowed.