getline not working with fstream

☆樱花仙子☆ 提交于 2019-12-11 06:59:57

问题


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();
}

回答1:


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.



来源:https://stackoverflow.com/questions/14777775/getline-not-working-with-fstream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!