简体   繁体   中英

Reading in from a .txt file to a struct array that contains enum

Here is my code

enum Status {IN, OUT };

const int TITLE_SIZE = 50, ISBN_SIZE = 13, AUTHOR_SIZE = 25;

struct Info
{
    char title[TITLE_SIZE];
    char isbn[ISBN_SIZE];
    char author[AUTHOR_SIZE];
    Status inOrOut;
};

int main()
{
    fstream dataFile;
    string filename;
    int numOfBooks = 0;
    Info *test = 0;
    int enumHolder = 0;

    cout << "How many books does the file contain? ";
    cin >> numOfBooks;
    test = new Info[numOfBooks];

    cout << "Enter a file (with path) for input and output: ";
    cin >> filename;

    dataFile.open(filename.c_str(), ios::in );
    if (dataFile.fail())
    {
        cout << "Could not open file; closing program" << "\n";
        return 0;
    }

    for (int i=0; i < (numOfBooks-1); i++)
    {
        dataFile >> test[i].title;
        dataFile >> test[i].isbn;
        dataFile >> test[i].author;
        dataFile >> enumHolder;
        test[i].inOrOut = static_cast<Status>(enumHolder);
    }

   for (int j=0; j < (numOfBooks-1); j++)
    {
        cout << test[j].title << " ";
        cout << test[j].isbn << " ";
        cout << test[j].author << " ";
        cout << test[j].inOrOut << " ";
        cout << "\n";
    }

Here is the .txt file

The Book

012345678901

Guy Duder

1 THAT Article

210987654321

Mr. Dr. Professor

0

Here is the output

How many books does the file contain? 2

Enter a file (with path) for input and output: D:/Documents/input.txt

The Book 012345678901 0

Question

What does the dataFile stop reading in a the first test[i].author? Is using static_cast causing this?

In order to convert an enum to printable text and text to an enum, you need to use a lookup table or an associative array. You could use a switch statement, but that is not as easy to maintain.

See also: std::map . Search Stackoverflow for "c++ lookup table".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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