简体   繁体   English

C ++:将文本文件解析并读入数组

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

I was hoping that I could find some help here. 我希望我能在这里找到一些帮助。 I have an assignment due next week that involves reading a bunch of data from a txt file into an array, and then printing out the results. 我下周要完成一项任务,包括从txt文件中读取一堆数据到数组中,然后打印出结果。 The data is in the following format: 数据采用以下格式:

"Macbeth","William Shakespeare","41.04","161","23","978-88-5985-004-5" “麦克白”,“威廉·莎士比亚”,“41.04”,“161”,“23”,“978-88-5985-004-5”

"A Christmas Carol","Charles Dickens","98.74","167","547","978-26-2885-780-7". “圣诞颂歌”,“查尔斯狄更斯”,“98.74”,“167”,“547”,“978-26-2885-780-7”。 .

.

.

Each row has six pieces of information that I need to store for later use. 每行有六条信息需要存储以供以后使用。 I'm supposed write code that counts the number of lines of text we have in order to create a dynamic array of the correct size. 我应该编写代码来计算我们拥有的文本行数,以便创建一个正确大小的动态数组。 I've got that covered. 我已经满足了。 I've got 39 lines entries. 我有39行参赛作品。 Then I'm supposed to create a function that reads the txt file and saves all of that data to the corresponding object in the array that I created. 然后我应该创建一个函数来读取txt文件并将所有数据保存到我创建的数组中的相应对象。

I don't know what methods to use, and I've been looking around for tutorials and explanations for a few days. 我不知道使用什么方法,我一直在寻找教程和解释几天。 I have extremely limited experience with files and parsing, so excuse me if I'm a little inexperienced. 我对文件和解析的经验非常有限,所以如果我有点缺乏经验,请原谅。 Here's my code so far: 到目前为止,这是我的代码:

#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[])
{

}

So, to summarize my issues, I don't understand how to parse data from the text file into my array. 所以,总结一下我的问题,我不明白如何将文本文件中的数据解析到我的数组中。 A very big thank you in advance to anyone that could help! 非常感谢任何有帮助的人! Cheers. 干杯。

EDIT: I've tried fooling around with the code, and I think I made a step in the right direction, but I'm still a little lost. 编辑:我试过愚弄代码,我想我朝着正确的方向迈出了一步,但我仍然有点失落。 Here's what I have for the parseData function. 这是我对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;
        }
    }




}

Maybe you just need to know how to do something with each character in a string? 也许你只需要知道如何对字符串中的每个字符做一些事情?

Here's some code that goes through each character of a string building up words, then prints them individually. 这里有一些代码遍历字符串的每个字符,然后单独打印它们。 You'll notice that string has the same interface as vector ( str[i] , str.push_back(char) , str.size() , etc.). 您会注意到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;
}

The std::basic_string (alias for std::string ) reference is probably useful. std::basic_stringstd::string别名)引用可能很有用。

You can use a vector data structure to hold the book class. 您可以使用矢量数据结构来保存图书类。 vector records; 矢量记录;

(I highly recommend to use a vector (or a list) for that because it will avoid the double reading of the file because you wouldn't need to know the number of line at all.) (我强烈建议使用向量(或列表),因为它将避免双重读取文件,因为您根本不需要知道行数。)

To parse a line that has a fixed number of field, it easy in principle: 要解析具有固定数量字段的行,原则上很容易:

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.

}

I didn't test this code, I know there a lack of error-testing, but It shows a way to do it. 我没有测试这段代码,我知道缺少错误测试,但它显示了一种方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM