我目前正在创建一个读取ASCII文件的文件来读取二进制文件。它必须将数据放入名为Arragements和Customers的对象中。但是,缺少某些东西。它不会读取文件的第一行。
有被正确地(似乎)读取的一切,不同之处在于它不事实'吨读取文件的第一行的所有,而是它在末尾添加5个零,当它被认为不是任何那里。换句话说,它并不是在阅读所有内容。有什么重大错误吗?我正在将代码从更改 ASCII 文件更改为,而不是读取 BINARY 文件。如果它做了任何更改,我已经添加了readTicketsFromFile在写入读取ASCII文件时的样子。
以下是从ASCII读取时的代码:https://pastebin.com/WswHzpxM
文件格式为(总共10行): < nr(2)> <金额票(4)> <价格(3)> <标题(30)>
这是我要做的事情,"翻译"在BINARY中读取相同文件的代码(显然转换为BINARY文件):
#include <fstream> // ifstream, ofstream
#include <iostream> // cout
#include <cstring> // strcpy
#include <cstdlib> // (s)rand
using namespace std;
const int ARRLEN = 35;
// CLASSES
class Arrangement {
private:
char title[ARRLEN]; // Arrangement title/name
int price; // Price pr. ticket
int amountSpaces; // Amounts of spaces/tickets left
int amountSold; // Amounts of tickets sold so far
int totalTicketsOrdered; // Total amount of tickets
int totalCustomersOrdered; // Amount of customers wanting a ticket
public:
Arrangement();
void update(char titt[], int ant, int pri);
void updateAmountWishedTickets(int antBill);
void updateAmountSold(int ant);
bool needPull();
int amountLeft();
int amountOrdered();
void write()
{
cout
<< '\n' << price << "\t"
<< amountSpaces << "\t"
<< amountSold << "\t"
<< totalTicketsOrdered
<< "\t" << totalCustomersOrdered
<< '\t' << title;
}
};
// READ FROM FILE 1
void readTicketsFromFile() {
char title[ARRLEN];
int nr, amount, price; // Variables 3 first "spaces" of the file
int size = 0;
// post/linje på filen.
ifstream infile;
infile.open("tickets.res", ios::in | ios::binary);
if (infile.is_open()) {
infile.seekg(0, ios::end);
size = (int)infile.tellg() / sizeof(Arrangement);
cout << "\n# in file: " << size << endl; // Prints out: 10
// Read from file, supposed to read everything from the file
for (int i = 1; i <= size; i++) {
infile.seekg(i * sizeof(Arrangement));
infile.read((char *)& arrangementer[i], sizeof(Arrangement));
cout << '\n' << i << " read: \n";
arrangementer[i].write(); // Used to see what what's inside the object, 1. missing.
}
}
else cout << "Couldn't open the file";
infile.close();
}
int main() {
readTicketsFromFile();
return 0;
}
它看起来像什么: https://i.gyazo.com/69c5560766c33ebc15cac25e13b4de72.png
它看起来像什么: https://i.gyazo.com/a9081f65ff629f3b57cb2c20750087b5.png