Search code examples
c++vectorfstreamifstream

C++, reading chars into a vector<char> from a file, character by character


I am trying to read in the first 7 chars of a file named "board.txt" into a vector<'char> but I am having issues for some reason. I am not too familiar with C++ so any advice would be appreciated, here is the code I have so far

    //rack
int charCount = 0;
char ch;

ifstream rackIn("board.txt");

while(rackIn.get(ch) && charCount < 7){
    this->getMyRack().push_back(ch);
}

And here is the function getMyRack used in the code above:

vector<char> board::getMyRack(){
    return this->myRack;
}

myRack is a char vector

I tried to test this in my main using this:

for (int i = 0; i < test->getMyRack().size(); ++i){
    cout << test->getMyRack().at(i);
} 

but it does not output anything, why are the chars i am reading in not being added into my char vectors?


Solution

  • Because you don't put char in your vector. Your function getMyRack() returns vector but not address of your vector. You can add method to your class board for adding char, for example:

     void board::addChar(char c){
         this->myRack.push_back(c);
       }
    

    And then call this function:

     while(rackIn.get(ch) && charCount < 7){
        this->addChar(ch);   
      }
    

    Or change the return type of your function.