簡體   English   中英

C ++:將文本文件解析並讀入數組

[英]C++: Parsing and Reading Text File Into an Array

我希望我能在這里找到一些幫助。 我下周要完成一項任務,包括從txt文件中讀取一堆數據到數組中,然后打印出結果。 數據采用以下格式:

“麥克白”,“威廉·莎士比亞”,“41.04”,“161”,“23”,“978-88-5985-004-5”

“聖誕頌歌”,“查爾斯狄更斯”,“98.74”,“167”,“547”,“978-26-2885-780-7”。

每行有六條信息需要存儲以供以后使用。 我應該編寫代碼來計算我們擁有的文本行數,以便創建一個正確大小的動態數組。 我已經滿足了。 我有39行參賽作品。 然后我應該創建一個函數來讀取txt文件並將所有數據保存到我創建的數組中的相應對象。

我不知道使用什么方法,我一直在尋找教程和解釋幾天。 我對文件和解析的經驗非常有限,所以如果我有點缺乏經驗,請原諒。 到目前為止,這是我的代碼:

#include <fstream>
#include <iomanip>
#include <iostream>
#include <string>

using namespace std;


class Author
{
    public:

private:
    string fname, lname;

};

class Book
{
    friend ofstream& operator<<(ofstream&, Book);

        public:
        Book();

    private:
        string bookName;
        Author author;
        double price;
        int qtyOnHand;
        int qtySold;
        double revenue;
        string ISBN;

};

Book :: Book()
{

}

int getLineNumber(ifstream &);
void parseData(ifstream &, Book []);


//void sortBookList(Book[], int, int);


int main()
{
    int numberOfBooks;

    //open the file from which to read the data
    ifstream myFile;
    myFile.open("Book List.txt");
    //function to find out how many objects to create
    numberOfBooks = getLineNumber(myFile);

    //create an array with that many objects
    Book *bptr;
    bptr = new Book[numberOfBooks];
    //function to read information from file into array of objects
    parseData(myFile, bptr);

    //loop to call sorting function and output function based on 4 different criteria

    //close the file explicitly
    return 0;
}

int getLineNumber(ifstream &myFile)
{
    int counter = 0;
    string myString;


    while(!myFile.eof())
    {
        getline(myFile, myString);
        counter++;
    }

    myFile.close();

    counter --;
    return counter;
}

void parseData(ifstream &myFile, Book bookPtr[])
{

}

所以,總結一下我的問題,我不明白如何將文本文件中的數據解析到我的數組中。 非常感謝任何有幫助的人! 干杯。

編輯:我試過愚弄代碼,我想我朝着正確的方向邁出了一步,但我仍然有點失落。 這是我對parseData函數的用法。

void parseData(ifstream &myFile, Book bookPtr[])
{

    string dummyLine;

    string word, line;
    myFile.open("Book List.txt");
    getline(myFile, dummyLine);
    string data[6];

    while(!myFile.eof())
    {
        getline(myFile, line, '\n');

        for (size_t i = 0; i < line.size(); ++i)
        {
            char c = line[i];

            if(c == ',' || c == '\n')
            {
                if(!word.empty())
                {
                    data[i] = word;
                    word.clear();
                }
            }
            else
            {
                word += c;
            }


        }
        if(!word.empty())
        {
            //cout << word << endl;
        }
    }




}

也許你只需要知道如何對字符串中的每個字符做一些事情?

這里有一些代碼遍歷字符串的每個字符,然后單獨打印它們。 您會注意到stringvector具有相同的接口( str[i]str.push_back(char)str.size()等)。

// You'll need to include <iostream> and <string>

std::string example = "This is an example string";
std::string word;

// Notice how you can loop through a string just like a vector<char>
for(size_t i = 0; i < example.size(); ++i) {
    char c = example[i];

    // When we see whitespace, print the current word and clear it
    if(c == ' ' || c == '\t' || c == '\n') {
        // Don't print anything if we don't have a word
        if(!word.empty()) {
            std::cout << word << std::endl;
            word.clear();
        }
    } else {
        // Append the current character to the end of the string
        word += c; // or word.push_back(c)
    }
}
// In case the line doesn't end with whitespace
if(!word.empty()) {
    std::cout << word << std::endl;
}

std::basic_stringstd::string別名)引用可能很有用。

您可以使用矢量數據結構來保存圖書類。 矢量記錄;

(我強烈建議使用向量(或列表),因為它將避免雙重讀取文件,因為您根本不需要知道行數。)

要解析具有固定數量字段的行,原則上很容易:

int counter = 0;
string myString;


while(!myFile.eof())
{
    getline(myFile, myString);
    counter++;
}
counter --;

//Clear the error state flag
myFile.clear()

//Return to the beginning of the file:
myFile.seekg(ios_base::beg);


const int fieldCount = 5;
string field[fieldCount ];


string buffer= "";
char c = '\0';
for( int i = 0; i < counter; ++i ) {
    for( int j = 0; j < fieldCount; ++j ) {
        myFile.ignore(); //Ignore the first '"'
        //Read each character up to the second '"'
        while( myFile.good() && (c = myfile.get()) != '"' ) {
            buffer += c;
        }
        field[j] = buffer;
        buffer = "";
        if( j != fieldCount - 1 ) {
            myFile.ignore(); //Ignore the first ','
        }
    }

    //Use the fields here.

}

我沒有測試這段代碼,我知道缺少錯誤測試,但它顯示了一種方法。

暫無
暫無

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

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