2

I created a class:

    Data::Data(char szFileName[MAX_PATH]) {

    string sIn;
    int i = 1;

    ifstream infile;
    infile.open(szFileName);
    infile.seekg(0,ios::beg);

    std::vector<std::string> fileRows;
    while ( getline(infile,sIn ) )
    {
      fileRows.push_back(sIn);
    }
}

after that i created this:

std::vector<std::string> Data::fileContent(){
        return fileRows;
}

After that I would like to call this fileContent() somewhere, something like this:

Data name(szFileName);
MessageBox(hwnd, name.fileContent().at(0).c_str() , "About", MB_OK);

But this doesnt work... How to call this?

4
  • What is Adatkezeles? Commented Mar 18, 2013 at 11:50
  • 3
    I guess you want to make fileRows as member of Data? Commented Mar 18, 2013 at 11:50
  • sorry Adatkezeles = Data Data name(szFileName); MessageBox(hwnd, name.fileContent().at(0).c_str() , "About", MB_OK); and i got this error: terminate called after throwing an instance of 'std::out_of_range' what(): vector::_M_range_check Commented Mar 18, 2013 at 11:52
  • @David: Please use the edit link to update your question with this information. Also, you probably want Data::fileContent() to (a) be const-qualified and (b) to return std::vector<std::string> by reference. Commented Mar 18, 2013 at 11:55

2 Answers 2

2
std::vector<std::string> fileRows;
while ( getline(infile,sIn ) )
{
   fileRows.push_back(sIn);
}

does not work because you declare fileRows in the constructor, once the constructor ends fileRows is destroyed.

What you need to do is to move the fileRows declaration outside of the constructor and make it a class member:

class Data
{
...

   std::vector<std::string> fileRows;
};

then it will be shared by all functions in the class.

Sign up to request clarification or add additional context in comments.

Comments

1

You could do like this:

#include <string>
#include <vector>

class Data
{
public:
  Data(const std::string& FileName)  // use std::string instead of char array
  {
     // load data to fileRows
  }

  std::string fileContent(int index) const  // and you may don't want to return a copy of fiileRows
  {
      return fileRows.at(index);
  }

private:
    std::vector<std::string> fileRows;
};

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.