简体   繁体   English

从.txt文件读入包含枚举的结构数组

[英]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 这是.txt文件

The Book

012345678901 012345678901

Guy Duder 盖伊杜德

1 THAT Article 1那篇文章

210987654321 210987654321

Mr. Dr. Professor 教授博士

0 0

Here is the output 这是输出

How many books does the file contain? 该文件包含多少本书? 2 2

Enter a file (with path) for input and output: D:/Documents/input.txt 输入输入和输出的文件(带路径):D:/Documents/input.txt

The Book 012345678901 0 书012345678901 0

Question

What does the dataFile stop reading in a the first test[i].author? dataFile在第一个测试[i] .author中停止读取什么? Is using static_cast causing this? 使用static_cast导致这个?

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. 您可以使用switch语句,但这不容易维护。

See also: std::map . 另请参见: std::map Search Stackoverflow for "c++ lookup table". 搜索“c ++查找表”的Stackoverflow。

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

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