从 .txt 文件读入包含 enum 的结构数组 [英] 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
012345678901
盖伊·杜德
1那篇文章
210987654321
210987654321
先生教授博士
0
这是输出
该文件包含多少本书?2
How many books does the file contain? 2
输入一个文件(带路径)用于输入和输出:D:/Documents/input.txt
Enter a file (with path) for input and output: D:/Documents/input.txt
本书 012345678901 0
The Book 012345678901 0
问题
dataFile 在第一个 test[i].author 中停止读取什么?使用 static_cast 会导致这种情况吗?
What does the dataFile stop reading in a the first test[i].author? Is using static_cast causing this?
推荐答案
为了将 enum 转换为可打印的文本并将文本转换为 enum,您需要使用查找表或关联数组.您可以使用 switch
语句,但这并不容易维护.
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.
另见:std::map
.在 Stackoverflow 中搜索c++ 查找表".
See also: std::map
.
Search Stackoverflow for "c++ lookup table".
这篇关于从 .txt 文件读入包含 enum 的结构数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!