【问题标题】:Reading in from a txt file. Trouble parsing info从 txt 文件中读取。无法解析信息
【发布时间】:2014-03-20 04:58:06
【问题描述】:

我想从 txt 文件中读取乐谱。分数将进入一个结构。

struct playerScore
{
    char name[32];
    int score, difficulty;
    float time;
};

文本文件如下所示

赛斯 26.255 40 7

作为一行,其中每个项目后跟一个制表符。 (名称\t时间\t分数\t难度\n)

当我开始阅读文本时,我不知道如何告诉程序何时停止。分数文件可以是任意数量的行或分数条目。这是我尝试过的。

hs.open("scores.txt", ios_base::in);
hs.seekg(0, hs.beg);


if (hs.is_open())
    {
        int currpos = 0;
        while (int(hs.tellg()) != int(hs.end));
        {
                hs>> inScore.name;
                hs >> inScore.time;
                hs >> inScore.score;
                hs >> inScore.difficulty;
                hs.ignore(INT_MAX, '\n');
                AllScores.push_back(inScore);
                currpos = (int)hs.tellg();
        }
    }

我正在尝试创建一个循环,将一行代码读入数据的临时结构,然后将该结构推入结构向量。然后用输入指针的当前位置更新 currpos 变量。但是,循环只是卡在条件上并冻结。

【问题讨论】:

  • 尝试用 while(hs.good()) 替换你的 while(...)

标签: c++ file-io struct


【解决方案1】:

有很多方法可以做到这一点,但以下可能是您正在寻找的。声明一个 free-operator 来提取球员得分的单行定义:

std::istream& operator >>(std::istream& inf, playerScore& ps)
{
    // read a single line.
    std::string line;
    if (std::getline(inf, line))
    {
        // use a string stream to parse line by line.
        std::istringstream iss(line);
        if (!(iss.getline(ps.name, sizeof(ps.name)/sizeof(*ps.name), '\t') &&
             (iss >> ps.time >> ps.score >> ps.difficulty)))
        {
            // fails to parse a full record. set the top-stream fail-bit.
            inf.setstate(std::ios::failbit);
        }
    }
    return inf;
}

这样,您的读取代码现在可以执行此操作:

std::istream_iterator<playerScore> hs_it(hs), hs_eof;
std::vector<playerScore> scores(hs_it, hs_eof);

【讨论】:

    【解决方案2】:

    我认为您不能只从您的文件中>>。你认为它会花费一切直到\ t? :)

    您可以尝试使用 strtok() 来获取例如令牌 我猜它可以使用 '\t' 来分割字符串并通过这个函数获取每个变量需要的字符串的一部分 如果它 strtok() 不能那样工作,我猜你可以在子循环中复制到 '\t'

    【讨论】:

      【解决方案3】:

      你可以这样做

      playerScore s1;
      
      fstream file;
      file.open("scores.txt", ios::in | ios::out);
      while(!file.eof()) //For end of while loop
      {
          file.read(s1, sizeof(playerScore));//read data in one structure.
          AllScores.push_back(s1);
      }
      

      【讨论】:

      • 告诉你while (!file.eof())的人是正确的做法,请tell them they're wrong.。在 99.99% 的情况下,循环 std::istream::eof 是完全错误的。 (这不是 0.01% 的例外)。问你自己。你怎么知道file.read() 工作 在盲目假设它确实有效并将s1 推入容器中?
      猜你喜欢
      • 2015-04-19
      • 1970-01-01
      • 2018-08-06
      • 2015-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-16
      • 1970-01-01
      相关资源
      最近更新 更多