好吧,这段代码让我受不了了。
我的目标是从数据用逗号分隔的文件中读取数据,然后将该数据加载到应该是“剧院座位”列表的结构数组中。剧院座位具有一定的特征,如“位置”、“价格”和“地位”。价格不言自明。位置处理“座位”的行号和座位号。状态与它是否已售出有关。之后,我必须解释从数据文件中提取的数据,以显示用户输入特定选择后可以轻松操作的显示。但这不是我在这个问题中要表达的意思。 我的问题是,从数据文件加载数据结构的最佳方法是什么?
让我向您展示一些我正在读取的数据文件。
1, 1, 50, 0
1, 2, 50, 0
1, 3, 50, 0
1, 4, 50, 0
解释一下数据文件,第一个数字是“行”,第二个数字是该行的座位号,第三个数字是价格,最后一个数字(“0”)代表未售出的座位.如果购买了座位,则最终数字将为 1。
现在,这是我的代码。
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
#include <cstdlib>
#include <cstdio>
#include <conio.h>
using namespace std;
enum seatDimensions{ROWS = 10, SEATS_PER = 16};
//Structures
struct Location
{
int row;
int seatNumber;
};
struct Seat
{
Location seat_location[160];
double ticketPrice;
int status;
int patronID;
};
//GLOBALS
const int MAX = 16;
int main()
{
//arrays for our data
Seat seatList[160];
//INDEX
int index = 1;
//filestream
fstream dataIn;
dataIn.open("huntington_data.dat",ios::in);
if(dataIn.fail()) //same as if(dataIn.fail())
{
cout << "Unable to access the data file." << endl;
return 999;
}
string temp;
getline(dataIn,temp,',');
seatList[index].seat_location[index].row = atoi(temp.c_str());
getline(dataIn,temp,',');
seatList[index].seat_location[index].seatNumber = atoi(temp.c_str());
getline(dataIn,temp,',');
seatList[index].ticketPrice = atof(temp.c_str());
getline(dataIn,temp,'\n');
seatList[index].status = atoi(temp.c_str());
while(!dataIn.eof() && index < MAX)
{
index++;
getline(dataIn,temp,',');
seatList[index].seat_location[index].row = atoi(temp.c_str());
getline(dataIn,temp,',');
seatList[index].seat_location[index].seatNumber = atoi(temp.c_str());
getline(dataIn,temp,',');
seatList[index].ticketPrice = atof(temp.c_str());
getline(dataIn,temp,'\n');
seatList[index].status = atoi(temp.c_str());
}
getch ();
return 0;
}
现在,我必须显示座位是否已被占用。 显示应该是这样的,因为还没有座位被占用。
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 // 16 across
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
// 10 deep
我知道我没有正确输入我的数据,因为无论我如何尝试计算,我似乎都无法获得此显示。如果你能说出我哪里出错了,请告诉我。任何建议都会很棒。 另外,如果你有任何问题要问我,尽管问。考虑到这个问题,我试图尽可能具体,但我知道它仍然很模糊。 请帮忙。
编辑:感谢那些回答我问题的人。我最终使用我的数据结构走了一条非常不同的路线,但从答案中得到了很多。
最佳答案
你有一个问题,每个座位在一个数组中有一个位置,然后有一个位置数组:
你需要:
Location seat_location[160];
改为:
int seat_row;
int seal_num;
然后:
seatList[index].seat_location[index].row = atoi(temp.c_str());
变成:
seatList[index].seat_row = index / COLS ;
seatList[index].seat_num = index % COLS ;
您可能还想考虑将您的数据实际排列到与您的座位尺寸相同的二维数组中。
顺便说一句,根据我的 C 背景,我建议阅读整行并使用 sscanf,例如:
char temp[255]; // Use an appropriate maximum line length +3 for \r\n\0
fgets(dataIn, &temp);
sscanf(temp, "%d, %d, %d, %d", &.....
您也可以考虑使用正则表达式来实现这一点。
关于c++ - 在 C++ 中将数据从文件加载到数据结构并进行解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19486401/