【发布时间】:2018-06-13 09:50:42
【问题描述】:
我遇到了这个问题 - 当我尝试将整数的二进制写入文件时,它不会将其写入 Delivery 文件中。
我的整个想法是获取整数,将其转换为二进制,然后将其写入文件。之后,如果需要,我会回到程序中,写入一个新的整数值,然后将新值添加到已经写入的值中。即文件中的“5”,回来,写“3”,然后文件中有8。
代码如下:
#include <iostream>
#include <fstream>
#include <string>
#include <conio.h>
#include <stdlib.h>
#include <string.h>
using namespace std;
char answer;
struct PRODUCT {
string product_name;
int quantity;
PRODUCT() : product_name(""), quantity(0) {}
} product;
int main () {
fstream delivery_file("files/Delivery", ios::app | ios::in | ios::out | ios::binary);
do {
if (delivery_file.is_open()) {
cout << "\nPlease input the name of a product: ";
getline(cin, product.product_name);
cout << "\nPlease input the quantity of a product: ";
string str;
getline(cin, str);
product.quantity = atoi(str.c_str());
bool foundAndReplaced = false;
while (!delivery_file.eof())
{
PRODUCT temp_prod;
while (!delivery_file.eof())
{
char ch = delivery_file.get();
temp_prod.product_name += ch;
if (ch == 0)
{
break;
}
}
if (delivery_file.eof() && delivery_file.tellg() == ios::beg)
{
cout << "Error: Unexpected end of file.\n";
delivery_file.clear();
break;
}
if (temp_prod.product_name == product.product_name)
{
delivery_file.seekp(delivery_file.tellg());
delivery_file.read((char*)(temp_prod.quantity), sizeof(PRODUCT::quantity));
product.quantity += temp_prod.quantity;
delivery_file.write((char*)(product.quantity), sizeof(PRODUCT::quantity));
foundAndReplaced = true;
}
}
if (!foundAndReplaced)
{
delivery_file.write(product.product_name.c_str(), product.product_name.length() + 1);
delivery_file.write((char*)(&product.quantity), sizeof(product.quantity));
}
}
else {
cout << "Unable to open file";
}
cout << "Do you want to add more products? Y/N \n";
answer = 0;
while (answer != 'y' && answer != 'Y' && answer != 'n' && answer != 'N')
{
answer = _getch();
}
}
while(answer == 'Y' || answer == 'y');
delivery_file.close();
cout << "\nDeliveries registered.\n";
return 0;
}
【问题讨论】:
-
不要发布外部链接。这些可能会过时。在此处发布您的代码(编辑您的问题)。只需将其添加到问题中,选择代码并按下编辑器中的
{}工具栏按钮即可。这会将其格式化为代码。更多信息:meta.stackexchange.com/questions/22186/…。我从您的链接中复制了代码并将其发布在此处。下次,你应该自己做。