Search code examples
c++fstreamgetline

getline not working with fstream


I am trying to use a text file to initialise a struct that will be used to initialise a 2d vector, yes I know it's complicated but there is going to be a lot of data to work with eventually. The problem is with getline, I have used it this way fine in other code but for some reason it's refusing to work here. I keep getting an argument error and template error. Any hints would be very much appreciated.

#include <fstream>
#include <string>
#include <vector>
#include <iostream>

using namespace std;

const int HORIZROOMS=10;
const int VERTROOMS=10;
const int MAXDESCRIPTIONS=20;
const int MAXEXITS=6;

struct theme
{
    string descriptions[MAXDESCRIPTIONS];
    string exits[MAXEXITS];
};

void getTheme();

int _tmain(int argc, _TCHAR* argv[])
{
    getTheme();
    vector<vector <room>> rooms(HORIZROOMS, vector<room>(VERTROOMS));
    for (int i=0; i<HORIZROOMS; i++)
    {
        for (int j=0; j<VERTROOMS; j++)
        {
            cout<<i<<" "<<j<<" "<<rooms[i][j].getRoomDescription()<<endl;
        }
    }
    return 0;
}

void getTheme()
{
    theme currentTheme;
    string temp;
    int numDescriptions;
    int numExits;
    ifstream themeFile("zombie.txt");
    getline(themeFile, numDescriptions, ',');
    for (int i=0; i<numDescriptions; i++)
    {
        getline(themeFile, temp, ',');
        currentTheme.descriptions[i]=temp;
    }
    getline(themeFile, numExits, ',');
    for (int i=0; i<numExits; i++)
    {
        getline(themeFile, temp, ',');
        currentTheme.exits[i]=temp;
    }
    themeFile.close();
}

Solution

  • std::getline is used to extract from a stream to a std::string. When you extract to numDescriptions and numExits, what you actually want is operator>>. For example,

    themeFile >> numDescriptions;
    

    This will automatically stop extracting at the following ,. However, you will need to skip over this comma if you don't want it to appear in the next std::getline extraction:

    themeFile.ignore();
    

    Alternatively, you could have a std::string numDescriptionsString which you do std::getline(themeFile, numDescriptionsString, ',') with and then convert that std::string to an int with std::stoi:

    getline(themeFile, numDescriptionsString, ',');
    numDescriptions = std::stoi(numDescriptionsString);
    

    I would say this is uglier though.