user249806
user249806

Reputation: 299

Why reading a std::string from file input returns blanks?

I am looking to return a string from a class.

I have an object like:

.....
using namespace std;
class inputFile{
private:

fstream  _file; 
bool  _exists;
std::string _inFileName;  // the filename
std::string _fileContents;

protected:

public:
inputFile(std::string*);
std::string getFileContents();
};

constructor:

inputFile::inputFile(std::string *in)
{
   _inFileName=*in;

   _file.open(_inFileName.c_str(),ios_base::in);
   while(_file.good()){
      getline(_file,_fileContents);

   cout << _fileContents << endl;
}

if(_file.is_open())
   _exists=true;
else
  _exists=false;
}

My method to return _fileContents always returns null instead of the file's contents i am reading in. why is this?

std::string inputFile::getFileContents(){
    return _fileContents;
}

driver.cpp:

meshfile=new inputFile("test.txt")
std::cout << meshFile->getFileContents() << std::endl;

returns blanks

Upvotes: 0

Views: 93

Answers (1)

facetus
facetus

Reputation: 1138

You don't save lines in _fileContents. You overwrite it every time. You have to append every line using _fileContents.append or operator +=.

class inputFile{
private:
    fstream  _file;
    bool  _exists;
    std::string _inFileName;  // the filename
    std::string _fileContents;

protected:

public:
    inputFile(std::string* in) {
        _inFileName = *in;

        _file.open(_inFileName.c_str(), ios_base::in);
        while (_file.good()) {
            std::string line;
            getline(_file, line);
            _fileContents += line;
        }

        cout << _fileContents << endl;
    }
    std::string getFileContents();
};

Upvotes: 1

Related Questions