#include
#include
#include
#include // для использования функции toupper()
using namespace std;
struct Product {
char type; // 'S' для смартфона, 'L' для ноутбука
code
// Общие поля для всех типов продуктов
string name;
double price;
// Поля, специфичные для вариантов
union {
// Вариант 1: Смартфон
struct {
int camera_count; // количество камер
double battery_capacity; // емкость батареи
} smartphone;
// Вариант 2: Ноутбук
struct {
double screen_size; // размер экрана
int ram_size; // объем оперативной памяти
} laptop;
} details;
};
// Функция для добавления нового продукта
void addProduct(vector &products) {
Product product;
code
Assistant
do {
cout << "Enter product type (S - smartphone, L - laptop): ";
cin >> product.type;
// Приводим букву к верхнему регистру
product.type = toupper(product.type);
if (product.type != 'S' && product.type != 'L') {
cout << "Invalid product type! Please enter 'S' for smartphone or 'L' for laptop." << endl;
}
} while (product.type != 'S' && product.type != 'L');
// Запрашиваем название продукта
cout << "Enter product name: ";
cin.ignore(); // Очищаем буфер ввода после cin
getline(cin, product.name); // Получаем строку с именем
do {
cout << "Enter product price: ";
cin >> product.price;
if (product.price <= 0) {
cout << "Price must be greater than 0. Please enter again." << endl;
}
} while (product.price <= 0);
// Если это смартфон, запрашиваем специфичные поля для смартфона
if (product.type == 'S') {
do {
cout << "Enter the number of cameras: ";
cin >> product.details.smartphone.camera_count;
if (product.details.smartphone.camera_count <= 0) {
cout << "The number of cameras must be greater than 0. Please enter again." << endl;
}
} while (product.details.smartphone.camera_count <= 0);
do {
cout << "Enter battery capacity (in mAh): ";
cin >> product.details.smartphone.battery_capacity;
if (product.details.smartphone.battery_capacity <= 0) {
cout << "Battery capacity must be greater than 0. Please enter again." << endl;
}
} while (product.details.smartphone.battery_capacity <= 0);
// Если это ноутбук, запрашиваем специфичные поля для ноутбука
} else if (product.type == 'L') {
do {
cout << "Enter screen size (in inches): ";
cin >> product.details.laptop.screen_size;
if (product.details.laptop.screen_size <= 0) {
cout << "Screen size must be greater than 0. Please enter again." << endl;
}
} while (product.details.laptop.screen_size <= 0);
do {
cout << "Enter RAM size (in GB): ";
cin >> product.details.laptop.ram_size;
if (product.details.laptop.ram_size <= 0) {
cout << "RAM size must be greater than 0. Please enter again." << endl;
}
} while (product.details.laptop.ram_size <= 0);
}
// Добавляем продукт в вектор
products.push_back(product);
cout << "Product added successfully!" << endl;
}
// Функция для удаления продукта (индексация начинается с 1)
void removeProduct(vector &products) {
if (products.empty()) {
cout << "No products to remove." << endl;
return;
}
code
int index;
cout << "Enter the product number to remove (starting from 1): ";
cin >> index; // Запрашиваем номер продукта
// Проверяем корректность введенного индекса
if (index > 0 && index <= products.size()) {
products.erase(products.begin() + (index - 1)); // Удаляем продукт
cout << "Product removed!" << endl;
} else {
cout << "Invalid product number!" << endl; // Ошибка, если индекс некорректен
}
}
// Функция для вывода всех продуктов
void displayProducts(const vector &products) {
if (products.empty()) {
// Если нет продуктов, выводим сообщение
cout << "No products available." << endl;
return;
}
code
for (int i = 0; i < products.size(); ++i) {
cout << "Product #" << i + 1 << endl; // Выводим номер продукта начиная с 1
cout << "Name: " << products[i].name << endl;
cout << "Price: " << products[i].price << " USD" << endl;
// Если продукт - смартфон, выводим информацию для смартфона
if (products[i].type == 'S') {
cout << "Type: Smartphone" << endl;
cout << "Number of cameras: " << products[i].details.smartphone.camera_count << endl;
cout << "Battery capacity: " << products[i].details.smartphone.battery_capacity << " mAh" << endl;
// Если продукт - ноутбук, выводим информацию для ноутбука
} else if (products[i].type == 'L') {
cout << "Type: Laptop" << endl;
cout << "Screen size: " << products[i].details.laptop.screen_size << " inches" << endl;
cout << "RAM size: " << products[i].details.laptop.ram_size << " GB" << endl;
}
cout << "--------------------" << endl; // Разделитель между продуктами
}
}
// Функция для вывода только смартфонов
void displaySmartphones(const vector &products) {
bool found = false; // Переменная для проверки наличия смартфонов
code
for (int i = 0; i < products.size(); ++i) {
if (products[i].type == 'S') {
// Проверяем, является ли продукт смартфоном
found = true; // Нашли хотя бы один смартфон
cout << "Smartphone #" << i + 1 << endl;
cout << "Name: " << products[i].name << endl;
cout << "Price: " << products[i].price << " USD" << endl;
cout << "Number of cameras: " << products[i].details.smartphone.camera_count << endl;
cout << "Battery capacity: " << products[i].details.smartphone.battery_capacity << " mAh" << endl;
cout << "--------------------" << endl;
}
}
if (!found) {
// Если смартфоны не найдены
cout << "No smartphones available." << endl;
}
}
// Функция для вывода только ноутбуков
void displayLaptops(const vector &products) {
bool found = false; // Переменная для проверки наличия ноутбуков
code
for (int i = 0; i < products.size(); ++i) {
if (products[i].type == 'L') {
// Проверяем, является ли продукт ноутбуком
found = true; // Нашли хотя бы один ноутбук
cout << "Laptop #" << i + 1 << endl;
cout << "Name: " << products[i].name << endl;
cout << "Price: " << products[i].price << " USD" << endl;
cout << "Screen size: " << products[i].details.laptop.screen_size << " inches" << endl;
cout << "RAM size: " << products[i].details.laptop.ram_size << " GB" << endl;
cout << "--------------------" << endl;
}
}
if (!found) {
// Если ноутбуки не найдены
cout << "No laptops available." << endl;
}
}
// Основное меню программы
void menu() {
vector products;
int choice;
code
// Бесконечный цикл для работы меню
do {
// Выводим список опций
cout << "1. Add new product" << endl;
cout << "2. Remove a product" << endl;
cout << "3. Display all products" << endl;
cout << "4. Display all smartphones" << endl;
cout << "5. Display all laptops" << endl;
cout << "0. Exit" << endl;
cout << "Choose an option: ";
cin >> choice;
// Обрабатываем выбор пользователя
switch (choice) {
case 1:
addProduct(products); // Добавить продукт
break;
case 2:
removeProduct(products); // Удалить продукт
break;
case 3:
displayProducts(products); // Показать все продукты
break;
case 4:
displaySmartphones(products); // Показать только смартфоны
break;
case 5:
displayLaptops(products); // Показать только ноутбуки
break;
case 0:
cout << "Exiting..." << endl; // Выход из программы
break;
default:
cout << "Invalid option!" << endl; // Ошибка при неверной опции
break;
}
} while (choice != 0);
}
int main() {
menu(); // Запуск меню
return 0;
}
перепиши, используя стандартный язык си, без каких-либо функций си++
c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdbool.h>
typedef struct {
char type; // 'S' for smartphone, 'L' for laptop
char name[100]; // Use a fixed-size array for the product name
double price;
union {
struct {
int camera_count;
double battery_capacity;
} smartphone;
struct {
double screen_size;
int ram_size;
} laptop;
} details;
} Product;
typedef struct {
Product *array;
int size;
int capacity;
} ProductList;
// Function to initialize the product list
void initProductList(ProductList *plist) {
plist->capacity = 10;
plist->size = 0;
plist->array = (Product *)malloc(plist->capacity * sizeof(Product));
if (plist->array == NULL) {
printf("Error allocating memory.\n");
exit(1);
}
}
// Function to resize the product list when capacity is reached
void resizeProductList(ProductList *plist) {
plist->capacity *= 2;
plist->array = (Product *)realloc(plist->array, plist->capacity * sizeof(Product));
if (plist->array == NULL) {
printf("Error reallocating memory.\n");
exit(1);
}
}
// Function to add a new product
void addProduct(ProductList *plist) {
Product product;
char buffer[100];
do {
printf("Enter product type (S - smartphone, L - laptop): ");
scanf(" %c", &product.type);
while (getchar() != '\n'); // Clear input buffer
product.type = toupper(product.type);
if (product.type != 'S' && product.type != 'L') {
printf("Invalid product type! Please enter 'S' for smartphone or 'L' for laptop.\n");
}
} while (product.type != 'S' && product.type != 'L');
// Read product name
printf("Enter product name: ");
fgets(product.name, sizeof(product.name), stdin);
// Remove the newline character at the end
product.name[strcspn(product.name, "\n")] = '\0';
// Read product price
do {
printf("Enter product price: ");
fgets(buffer, sizeof(buffer), stdin);
if (sscanf(buffer, "%lf", &product.price) != 1 || product.price <= 0) {
printf("Price must be greater than 0. Please enter again.\n");
}
} while (product.price <= 0);
// Read product-specific details
if (product.type == 'S') {
do {
printf("Enter the number of cameras: ");
fgets(buffer, sizeof(buffer), stdin);
if (sscanf(buffer, "%d", &product.details.smartphone.camera_count) != 1 || product.details.smartphone.camera_count <= 0) {
printf("The number of cameras must be greater than 0. Please enter again.\n");
}
} while (product.details.smartphone.camera_count <= 0);
do {
printf("Enter battery capacity (in mAh): ");
fgets(buffer, sizeof(buffer), stdin);
if (sscanf(buffer, "%lf", &product.details.smartphone.battery_capacity) != 1 || product.details.smartphone.battery_capacity <= 0) {
printf("Battery capacity must be greater than 0. Please enter again.\n");
}
} while (product.details.smartphone.battery_capacity <= 0);
} else if (product.type == 'L') {
do {
printf("Enter screen size (in inches): ");
fgets(buffer, sizeof(buffer), stdin);
if (sscanf(buffer, "%lf", &product.details.laptop.screen_size) != 1 || product.details.laptop.screen_size <= 0) {
printf("Screen size must be greater than 0. Please enter again.\n");
}
} while (product.details.laptop.screen_size <= 0);
do {
printf("Enter RAM size (in GB): ");
fgets(buffer, sizeof(buffer), stdin);
if (sscanf(buffer, "%d", &product.details.laptop.ram_size) != 1 || product.details.laptop.ram_size <= 0) {
printf("RAM size must be greater than 0. Please enter again.\n");
}
} while (product.details.laptop.ram_size <= 0);
}
// Add the product to the list
if (plist->size == plist->capacity) {
resizeProductList(plist);
}
plist->array[plist->size++] = product;
printf("Product added successfully!\n");
}
// Function to remove a product by its index
void removeProduct(ProductList *plist) {
if (plist->size == 0) {
printf("No products to remove.\n");
return;
}
int index;
char buffer[100];
printf("Enter the product number to remove (starting from 1): ");
fgets(buffer, sizeof(buffer), stdin);
if (sscanf(buffer, "%d", &index) != 1 || index <= 0 || index > plist->size) {
printf("Invalid product number!\n");
return;
}
// Remove the product by shifting elements
for (int i = index - 1; i < plist->size - 1; ++i) {
plist->array[i] = plist->array[i + 1];
}
plist->size--;
printf("Product removed!\n");
}
// Function to display all products
void displayProducts(const ProductList *plist) {
if (plist->size == 0) {
printf("No products available.\n");
return;
}
for (int i = 0; i < plist->size; ++i) {
printf("Product #%d\n", i + 1);
printf("Name: %s\n", plist->array[i].name);
printf("Price: %.2lf USD\n", plist->array[i].price);
if (plist->array[i].type == 'S') {
printf("Type: Smartphone\n");
printf("Number of cameras: %d\n", plist->array[i].details.smartphone.camera_count);
printf("Battery capacity: %.2lf mAh\n", plist->array[i].details.smartphone.battery_capacity);
} else if (plist->array[i].type == 'L') {
printf("Type: Laptop\n");
printf("Screen size: %.2lf inches\n", plist->array[i].details.laptop.screen_size);
printf("RAM size: %d GB\n", plist->array[i].details.laptop.ram_size);
}
printf("--------------------\n");
}
}
// Function to display only smartphones
void displaySmartphones(const ProductList *plist) {
bool found = false;
for (int i = 0; i < plist->size; ++i) {
if (plist->array[i].type == 'S') {
found = true;
printf("Smartphone #%d\n", i + 1);
printf("Name: %s\n", plist->array[i].name);
printf("Price: %.2lf USD\n", plist->array[i].price);
printf("Number of cameras: %d\n", plist->array[i].details.smartphone.camera_count);
printf("Battery capacity: %.2lf mAh\n", plist->array[i].details.smartphone.battery_capacity);
printf("--------------------\n");
}
}
if (!found) {
printf("No smartphones available.\n");
}
}
// Function to display only laptops
void displayLaptops(const ProductList *plist) {
bool found = false;
for (int i = 0; i < plist->size; ++i) {
if (plist->array[i].type == 'L') {
found = true;
printf("Laptop #%d\n", i + 1);
printf("Name: %s\n", plist->array[i].name);
printf("Price: %.2lf USD\n", plist->array[i].price);
printf("Screen size: %.2lf inches\n", plist->array[i].details.laptop.screen_size);
printf("RAM size: %d GB\n", plist->array[i].details.laptop.ram_size);
printf("--------------------\n");
}
}
if (!found) {
printf("No laptops available.\n");
}
}
// Main menu function
void menu() {
ProductList products;
initProductList(&products);
int choice;
char buffer[100];
do {
printf("1. Add new product\n");
printf("2. Remove a product\n");
printf("3. Display all products\n");
printf("4. Display all smartphones\n");
printf("5. Display all laptops\n");
printf("0. Exit\n");
printf("Choose an option: ");
fgets(buffer, sizeof(buffer), stdin);
if (sscanf(buffer, "%d", &choice) != 1) {
printf("Invalid input!\n");
continue;
}
switch (choice) {
case 1:
addProduct(&products);
break;
case 2:
removeProduct(&products);
break;
case 3:
displayProducts(&products);
break;
case 4:
displaySmartphones(&products);
break;
case 5:
displayLaptops(&products);
break;
case 0:
printf("Exiting...\n");
break;
default:
printf("Invalid option!\n");
break;
}
} while (choice != 0);
// Free allocated memory
free(products.array);
}
int main() {
menu();
return 0;
}
Explanation:
Standard C Structures: The Product and ProductList structures are defined using standard C syntax. The Product structure contains common fields and a union for specific details.
Dynamic Array Management: Instead of C++ vectors, we use dynamic arrays in C. The initProductList function initializes the product list, and resizeProductList resizes it when necessary.
Input Handling: All user inputs are handled using standard C functions like scanf, printf, fgets, and sscanf. Care is taken to clear input buffers and handle newline characters.
Menu and Operations: The menu function provides a simple text-based interface, allowing users to add, remove, and display products. Each operation is implemented in a separate function for clarity.
Memory Management: Memory allocated for the product list is freed before exiting the program to prevent memory leaks.
This code provides the same functionality as the original C++ code but is rewritten entirely using standard C. It avoids all C++ features such as iostream, std::string, and std::vector, utilizing C equivalents instead.