Поскольку в функции createProduct при обновлении продукта, когда обновление истинно, она создает еще один дубликат продукта или вызывает завершение после создания экземпляра 'std::bad_alloc'
what (): std::bad_alloc
Он работает при добавлении продуктов, но не при обновлении, поскольку он дублирует какое-то значение или вызывает ошибку завершения после создания экземпляра 'std::bad_alloc ' появляется What(): std::bad_alloc
Прилагаю полный код
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
void generateAdminMenu();
const string &productsFilename = "products.bin";
const string &usersFilename = "users.bin";
struct Product
{
int id;
float salePrice;
string name;
void saveProduct(ofstream &file) const
{
size_t lengthName = name.size();
file.write(reinterpret_cast(&id), sizeof(id));
file.write(reinterpret_cast(&salePrice), sizeof(salePrice));
file.write(reinterpret_cast(&lengthName), sizeof(lengthName));
file.write(name.c_str(), lengthName);
}
void readProducts(ifstream &file)
{
size_t lengthName;
file.read(reinterpret_cast(&id), sizeof(id));
file.read(reinterpret_cast(&salePrice), sizeof(salePrice));
file.read(reinterpret_cast(&lengthName), sizeof(lengthName));
name.resize(lengthName);
file.read(&name[0], lengthName);
}
void saveProduct(fstream &file) const
{
size_t lengthName = name.size();
file.write(reinterpret_cast(&id), sizeof(id));
file.write(reinterpret_cast(&salePrice), sizeof(salePrice));
file.write(reinterpret_cast(&lengthName), sizeof(lengthName));
file.write(name.c_str(), lengthName);
}
void readProduct(fstream &file)
{
size_t lengthName;
file.read(reinterpret_cast(&id), sizeof(id));
file.read(reinterpret_cast(&salePrice), sizeof(salePrice));
file.read(reinterpret_cast(&lengthName), sizeof(lengthName));
name.resize(lengthName);
file.read(&name[0], lengthName);
}
};
int getLatestProductId()
{
int lastId = 0;
ifstream file(productsFilename, ios::binary);
while (file.peek() != EOF)
{
Product product;
product.readProducts(file);
if (product.id != -1)
{
lastId = product.id;
}
}
file.close();
return lastId;
}
void createProduct(bool update = false, int productId = 0)
{
cin.ignore();
Product product;
cout
Подробнее здесь: https://stackoverflow.com/questions/791 ... dbad-alloc
Вызов экземпляра 'std::bad_alloc' What(): std::bad_alloc ⇐ C++
Программы на C++. Форум разработчиков
-
Anonymous
1729926025
Anonymous
Поскольку в функции createProduct при обновлении продукта, когда обновление истинно, она создает еще один дубликат продукта или вызывает завершение после создания экземпляра 'std::bad_alloc'
what (): std::bad_alloc
Он работает при добавлении продуктов, но не при обновлении, поскольку он дублирует какое-то значение или вызывает ошибку завершения после создания экземпляра 'std::bad_alloc ' появляется What(): std::bad_alloc
Прилагаю полный код
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
void generateAdminMenu();
const string &productsFilename = "products.bin";
const string &usersFilename = "users.bin";
struct Product
{
int id;
float salePrice;
string name;
void saveProduct(ofstream &file) const
{
size_t lengthName = name.size();
file.write(reinterpret_cast(&id), sizeof(id));
file.write(reinterpret_cast(&salePrice), sizeof(salePrice));
file.write(reinterpret_cast(&lengthName), sizeof(lengthName));
file.write(name.c_str(), lengthName);
}
void readProducts(ifstream &file)
{
size_t lengthName;
file.read(reinterpret_cast(&id), sizeof(id));
file.read(reinterpret_cast(&salePrice), sizeof(salePrice));
file.read(reinterpret_cast(&lengthName), sizeof(lengthName));
name.resize(lengthName);
file.read(&name[0], lengthName);
}
void saveProduct(fstream &file) const
{
size_t lengthName = name.size();
file.write(reinterpret_cast(&id), sizeof(id));
file.write(reinterpret_cast(&salePrice), sizeof(salePrice));
file.write(reinterpret_cast(&lengthName), sizeof(lengthName));
file.write(name.c_str(), lengthName);
}
void readProduct(fstream &file)
{
size_t lengthName;
file.read(reinterpret_cast(&id), sizeof(id));
file.read(reinterpret_cast(&salePrice), sizeof(salePrice));
file.read(reinterpret_cast(&lengthName), sizeof(lengthName));
name.resize(lengthName);
file.read(&name[0], lengthName);
}
};
int getLatestProductId()
{
int lastId = 0;
ifstream file(productsFilename, ios::binary);
while (file.peek() != EOF)
{
Product product;
product.readProducts(file);
if (product.id != -1)
{
lastId = product.id;
}
}
file.close();
return lastId;
}
void createProduct(bool update = false, int productId = 0)
{
cin.ignore();
Product product;
cout
Подробнее здесь: [url]https://stackoverflow.com/questions/79127976/throwing-an-instance-of-stdbad-alloc-what-stdbad-alloc[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия