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

拜拜、爱过 提交于 2020-01-17 12:14:04

问题


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?


回答1:


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".



来源:https://stackoverflow.com/questions/28531933/reading-in-from-a-txt-file-to-a-struct-array-that-contains-enum

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!