0

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

2
  • 1
    If you assign a value to a boolean variable, which exactly matches the result of a preceding if-statement (if (cond)), you should assign the result of the condition directly to the variable (bool_var = cond)
    – 0xbadf00d
    Dec 19, 2014 at 23:44
  • thanks for the tip. makes perfect sense
    – user249806
    Dec 22, 2014 at 14:17

1 Answer 1

1

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();
};
1
  • Ahhh and rhat explains why the cout in the while statement always output the info. Then the cout in the method returned a newline. Thanks
    – user249806
    Dec 20, 2014 at 1:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.