【问题标题】:Reading in from a .txt file to a struct array that contains enum从 .txt 文件读入包含枚举的结构数组
【发布时间】:2015-04-16 09:41:06
【问题描述】:

这是我的代码

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

问题

在第一个测试[i]中的数据文件停止阅读.Author?是使用 static_cast 造成的吗?

【问题讨论】:

    标签: c++ file structure static-cast


    【解决方案1】:

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

    另请参阅:std::map。 在 Stackoverflow 中搜索“c++ 查找表”。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-02-15
      • 1970-01-01
      • 1970-01-01
      • 2013-12-14
      • 1970-01-01
      • 2023-03-07
      • 1970-01-01
      相关资源
      最近更新 更多