C ++将.text文件列读入数组

时间:2013-06-20 03:41:53

标签: c++ arrays sorting filestream

大家好,我不是C ++的新手,但我的技能不是很好。无论如何,我有一个我无法按时完成的任务,而且我无法让我的代码工作。现在我只想完成它,以便我知道如何进行未来的任务。

数据文件包含同一行的玩家数量及其得分,最后一列是他们的时间。

问题是,有一个.txt文件,我必须在我的程序中打开,这个文件读作(没有项目符号)。

  • 27
  • pop 23 45 92 34 43 125
  • 警察4 23 56 23 75 323
  • ......等等。

如何存储/忽略第一个变量,然后逐列创建数据列(以空格分隔)?

这是我创造的。我已经创建了需要将相应数据存储到的数组。

#include <iostream>
#include <cmath>
#include <ctime>
#include <iomanip>
#include <vector>
#include <string>
#include <sstream>
#include <fstream>
using namespace std;

int main()
{
    cout<<"Welcome to the Score Sorting Program! \n";
    cout<<"Please choose a number that corresponds with the way you would like to  sort. \n";
    cout<<"You may also search by player if you know their username. \n";

    string players[50]; //Allocated space for 50 players.
    int score1[27]; //Array for Score 1
    int score2[27]; //
    int score3[27]; //
    int score4[27]; //
    int score5[27]; //
    int time[27];   //Array for Time
    int i = 0;
    int j = 0;

    ifstream myfile;
    myfile.open("G2347M.txt");
    if (!myfile)
    {
         cout<<"Could not open file. \n";
         system ("Pause");
         return -1;
    }  

    while (!myfile.eof())
    {
        getline(myfile, players[i], ' ');
        if (i == 26)
        {
            i=0;
            ++j;
            getline(myfile, players[i],' ');
        }
        i++;
    }    

}

所以基本上我会将玩家的分数与输出对齐到另一个文件。 我只是希望阅读文件的第一部分,然后我将继续。

我已经研究了类似的主题(4小时+),试图拼凑代码以让我的工作。我将继续研究和更新我能做的任何事情。

3 个答案:

答案 0 :(得分:0)

为什么有50名球员,但只有27分?

我假设第一行是您期望阅读的总行数?如果是这样,您可以动态分配数组来保存所有数据,而不仅仅处理50(或27)行。您还可以将一行的所有数据组合到一个结构中,而不是将其分布在一堆断开连接的数组上。

伪代码:

int lineNo = 1;
int totalLines = -1; /* not set */

while(line = read_a_line()) {
    if (lineNo == 1) {
        totalLines = convert_line_text_to_number();
    }
    else {
        /* split the line into "tokens" separated by white space */
        /* store each token in the correct array */
    }
    lineNo++;
    /* if lineNo is too big, break the loop */
}

答案 1 :(得分:0)

使用它的最佳方式是使用向量。但正如你告诉你必须使用Arrays所以这里是代码。

#include <iostream>
#include <fstream>
#include <sstream>

using namespace std;

int main()
{
    ifstream file;
    file.open("sample.txt");

    string name[50];
    int score1[27],score2[27],score3[27],score4[27],score5[27],time[27];


    int i = 0;
    while(!file.eof())
    {
        string line;
        getline(file,line);
        char* a = const_cast<char*>(line.c_str());  
        char* pch = strtok (a," ");

        name[i] = pch;
        int counter = 1;
        while (counter < 7)
        {
            pch = strtok (NULL, " ");

            if(counter == 1)
            {
                score1[i] = atoi(pch);
            }
            else if(counter == 2)
            {
                score2[i] = atoi(pch);
            }
            else if(counter == 3)
            {
                score3[i] = atoi(pch);
            }
            else if(counter == 4)
            {
                score4[i] = atoi(pch);
            }
            else if(counter == 5)
            {
                score5[i] = atoi(pch);
            }
            else if(counter == 6)
            {
                time[i] = atoi(pch);
            }

            ++counter;
        }

        ++i;
    }

    //cout<<a;
    return 0;
}

如果您遇到任何问题,请与我们联系。我没有添加一些基本的健全性检查,例如一个用于文件,请在您的版本中执行此操作。

答案 2 :(得分:0)

这是一种使用运算符&gt;&gt;的封装和重载的方法。我假设您为输入描述的内容只是一长串空格分隔的输入值,第一个值是玩家的数量。

#include <iostream>
#include <iomanip>
#include <string>
#include <sstream>
#include <fstream>
#include <ctype.h>

using namespace std;

static const size_t MaxNumPlayers = 50;

// C++ is about encapsulation, and the player data is
// discrete yet related, so encapsulate it.
struct Player
{
    string m_name;
    int m_scores[5];
    size_t GetNumScores() const { return sizeof(m_scores) / sizeof(m_scores[0]); }
    int m_time;
};

// This allows us to write an operator that will read a player
// directly from an ifstream.
std::ifstream& operator>>(ifstream& istr, Player& player)
{
    istr >> player.m_name;
    for(size_t i = 0; i < player.GetNumScores(); ++i)
    {
       istr >> player.m_scores[i];
    }
    istr >> player.m_time;
    cout << "player: " << player.m_name << ", " << player.m_scores[0] << " @ " << player.m_time << endl;
    return istr;
}

int main(int argc, const char** argv)
{
    ifstream myfile("G2347M.txt");
    if (!myfile)
    {
         cout<<"Could not open file. \n";
         system("Pause");
         return -1;
    }

    // We can read the number of players directly.
    size_t numPlayers = 0;
    myfile >> numPlayers;
    if (numPlayers <= 0 || numPlayers > MaxNumPlayers) {
        cout << "Invalid number of players in score file ("<<numPlayers<<")." << endl;
        system("Pause");
        return -1;
    }

    Player players[MaxNumPlayers];
    size_t playersRead = 0;

    while (!myfile.eof())
    {
        myfile >> players[playersRead++];
        if (playersRead >= numPlayers)
            break;
        // drain any spaces after the player.
        while(isspace(myfile.peek()))
          myfile.ignore();
    }

    if (playersRead != numPlayers)
    {
        cout << "Problem reading score file, expected " << numPlayers << " but read " << playersRead << endl;
        system("Pause");
        return -1;
    }

    cout<<"Welcome to the Score Sorting Program! I read "<<playersRead<<" players."<<endl;
    cout<<"Please choose a number that corresponds with the way you would like to sort."<<endl;
    cout<<"You may also search by player if you know their username.\n"<<endl;

    /* ... */

    system("Pause");
    return 0;
}