getline无法与fstream一起使用

getline无法与fstream一起使用

本文介绍了getline无法与fstream一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用文本文件初始化将用于初始化2d向量的结构,是的,我知道它很复杂,但最终将要处理大量数据.问题在于getline,我在其他代码中已经很好地使用了它,但是由于某种原因,它拒绝在这里工作.我不断收到参数错误和模板错误.任何提示将不胜感激.

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

推荐答案

std::getline用于从流中提取到std::string.当您提取到numDescriptionsnumExits时,实际需要的是operator>>.例如,

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;

这将自动在以下,处停止提取.但是,如果您不希望它出现在下一个std::getline提取中,则需要跳过该逗号:

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

或者,您可以使用一个std::string numDescriptionsString来执行std::getline(themeFile, numDescriptionsString, ','),然后使用std::stoi将该std::string转换为int:

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

我会说这很丑.

这篇关于getline无法与fstream一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 19:08