繁体   English   中英

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

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

这是我的代码

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";
    }

这是.txt文件

012345678901

盖伊杜德

1那篇文章

210987654321

教授博士

0

这是输出

该文件包含多少本书? 2

输入输入和输出的文件(带路径):D:/Documents/input.txt

书012345678901 0

dataFile在第一个测试[i] .author中停止读取什么? 使用static_cast导致这个?

为了将枚举转换为可打印的文本和文本到枚举,您需要使用查找表或关联数组。 您可以使用switch语句,但这不容易维护。

另请参见: std::map 搜索“c ++查找表”的Stackoverflow。

暂无
暂无

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

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