簡體   English   中英

C ++將.txt文件列讀入數組

[英]C++ Read .txt file columns into an array

大家好,我不是C ++的新手,但是我的技能不是很熟練。 無論如何,我有一個無法按時完成的任務,這讓我很煩,我無法使我的代碼正常工作。 現在我只想完成它,這樣我就可以知道將來的工作。

數據文件在同一行上包含玩家數量及其得分,最后一列是他們的時間。

問題是這樣的,我必須在程序中打開一個.txt文件,其內容應為this(沒有項目符號)。

  • 27
  • 流行23 45 92 34 43125
  • 締約方會議4 23 56 23 75323
  • ...等等。

如何存儲/忽略第一個變量,然后用數據逐列(由空格分隔)創建數組?

這是我創建的。 我創建了將各個數據存儲到的數組。

#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個小時),試圖將代碼拼湊起來以使我的工作正常。 我將繼續研究和更新。

為什么有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 */
}

最好的使用方式是向量。 但是正如您所說的,您必須使用數組,因此這里是代碼。

#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;
}

如果您遇到任何問題,請告訴我。 我沒有添加一些基本的健全性檢查,例如文件檢查,請在您的版本中進行檢查。

這是一種使用操作符>>的封裝和重載的方法。 我假設您所描述的輸入只是一長串由空格分隔的輸入值,第一個值是玩家數。

#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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM