getline无法使用fstream

getline not working with fstream

本文关键字:fstream getline      更新时间:2023-10-16

我正试图使用一个文本文件来初始化一个结构,该结构将用于初始化2d向量,是的,我知道这很复杂,但最终会有很多数据需要处理。问题是getline,我在其他代码中也用过这种方式,但由于某种原因,它拒绝在这里工作。我不断收到一个参数错误和模板错误。如有任何提示,我们将不胜感激。

#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>>。例如,

themeFile >> numDescriptions;

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

themeFile.ignore();

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

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

不过我想说这更难看。