getline没有按预期工作

时间:2013-07-17 06:45:17

标签: c++ while-loop text-files

我正在尝试使用类结构和getline()函数将文本文件数据显示到列中以读取文本文件并将数据转储到矢量类中。但似乎该程序甚至没有运行到我的'while'循环然后退出该程序。文本文件不为空。

以下是我的代码:

void ScrambleWordGame::displayScoreChart() {
//open file
fstream readScoreChart("ScoreChart.txt");
string line = "";

//vector to store data in
vector<personResult> perResult;
personResult person;

//while file is open, do stuff
if(readScoreChart.is_open())
{
    //check through the file
    readScoreChart.seekp(0,ios::end);
    //get the size of the file's data
    size_t size = readScoreChart.tellg();
    if(size == 0)
        cout << "No results yet. Please TRY to win a game. AT LEAST~" << endl;
    else
    {
        //create the 1st row with 4 column names
        cout << left
            << setw(20) << "Player Name "
            << setw(20) << "Winning Time "
            << setw(20) << "No. Of Attempts "
            << setw(20) << "Game Level " << endl;
        //fill the second line with dashes(create underline)
        cout << setw(70) << setfill('-') << "-" << endl;
        //read the file line by line
        //push the 1st line data into 'line'
        cout << getline(readScoreChart,line);
        while(getline(readScoreChart,line))
        {
            //create stringstream n push in the entire line in
            stringstream lineStream(line);

            //reads the stringstream and dump the data seperated by delimiter
            getline(lineStream,person.playerName,':');
            getline(lineStream,person.winningTime,':');
            getline(lineStream,person.noOfAttempts,':');
            getline(lineStream,person.gameLvl);

            //sort the results based on their timing
            //sort(perResult.begin(),perResult.end(),pRes);
            //display the results
            cout << left
                    << setfill(' ')
                    << setw(25) << person.playerName
                    << setw(22) << person.winningTime
                    << setw(17) << person.noOfAttempts
                    << setw(16) << person.gameLvl
                    << endl;
        }
    }
}
readScoreChart.close();

}

编辑:TextFile的示例
乔尔:3:1:1
玛丽:5:2:2
约翰:25:3:1

2 个答案:

答案 0 :(得分:2)

首次搜索后,您的文件指针位于文件的末尾。您需要将其重新定位到文件的开头。

if(size == 0)
{
    cout << "No results yet. Please TRY to win a game. AT LEAST~" << endl;
}
else
{
    readScoreChart.seekp(0,ios::begin);
    // all you other stuff
}

答案 1 :(得分:1)

您需要回到文件的开头才能阅读。更好的是,只是不要首先寻求最终目的。

我稍微重新构造代码 - 写一个operator>>来读取文件中的记录,然后operator<<将记录写入文件。

class person {
    std::string name;
    std::string winning_time;
    std::string num_attempts;
    std::string level;

 public:
    bool operator<(person const &other) const { 
        return std::stoi(winning_time) < std::stoi(other.winning_time);
    }

    friend std::istream &operator>>(std::istream &in, person &p) { 
            std::string buffer;
            std::getline(in, buffer);
            std::istringstream is(buffer);

            std::getline(is,p.name,':');
            std::getline(is,p.winning_time,':');
            std::getline(is,p.num_attempts,':');
            std::getline(is,p.level);
            return in;
    }

    friend std::ostream &operator<<(std::ostream &os, person const &p) { 
             return os << std::setw(25) << p.name
                       << std::setw(22) << p.winning_time
                       << std::setw(17) << p.num_attempts
                       << std::setw(16) << p.level;
    }

};

有了这些,剩下的就变得更简单了:

void show_header(std::ostream &os) { 
    cout << left
        << setw(20) << "Player Name "
        << setw(20) << "Winning Time "
        << setw(20) << "No. Of Attempts "
        << setw(20) << "Game Level " << "\n";
    std::cout << std::string(70, '-');
}

 void game::displayScoreChart(){ 
    std::ifstream in("ScoreChart.txt");

    // read the data:
    std::vector<person> people{std::istream_iterator<person>(in),
                               std::istream_iterator<person>()};

   if (people.empty()) {
       std::cout << "No scores yet."
       return;
   }

   // sort it by winning time:
   std::sort(people.begin(), people.end());

   show_header(std::cout);

   // display it:
   for (auto const &p : people) 
       std::cout << p << "\n";
   return 0;
}

作为一个简单的替代品,如果你没有C ++ 11编译器,stoi可以写成这样的东西:

int stoi(std::string in) { 
     return strtol(in.c_str(), NULL, 10);
}