【问题标题】:getline not working with fstreamgetline 不能与 fstream 一起使用
【发布时间】:2013-01-24 12:37:40
【问题描述】:

我正在尝试使用文本文件来初始化将用于初始化 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();
}

【问题讨论】:

  • 您只能将getline 与字符串一起使用。
  • 我可以建议类似tinyXML

标签: c++ fstream getline


【解决方案1】:

std::getline 用于从流中提取到std::string。当你提取到numDescriptionsnumExits 时,你真正想要的是operator&gt;&gt;。例如,

themeFile >> numDescriptions;

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

themeFile.ignore();

或者,你可以有一个std::string numDescriptionsString,你可以使用std::getline(themeFile, numDescriptionsString, ','),然后将std::string转换为int,使用std::stoi

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

我会说这更丑。

【讨论】:

  • 完美,解决了这个问题,现在继续使用它来创建我的对象向量的问题。有时我希望我还在使用 python。
  • @Modred 祝你好运——应该不会太难。你得到的练习越多,你对 C++ 的使用就会越好。 Python 也是一门很棒的语言。无论如何,如果我的回答有帮助,请不要忘记接受它。谢谢。
猜你喜欢
  • 2013-01-16
  • 1970-01-01
  • 1970-01-01
  • 2016-02-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-21
  • 1970-01-01
相关资源
最近更新 更多