Загрузка данных
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Program
{
static Dictionary<string, int> warehouse = new Dictionary<string, int>();
static string fileName = "warehouse.txt";
static void Main()
{
LoadWarehouse();
bool running = true;
while (running)
{
Console.WriteLine("\n--- Склад ---");
Console.WriteLine("1. Добавить товар");
Console.WriteLine("2. Продать товар");
Console.WriteLine("3. Показать все товары");
Console.WriteLine("4. Выход");
Console.Write("Выберите действие: ");
string choice = Console.ReadLine();
switch (choice)
{
case "1":
AddProduct();
break;
case "2":
SellProduct();
break;
case "3":
ShowAllProducts();
break;
case "4":
running = false;
break;
default:
Console.WriteLine("Неверный ввод.");
break;
}
}
}
static void LoadWarehouse()
{
if (File.Exists(fileName))
{
var lines = File.ReadAllLines(fileName);
foreach (var line in lines)
{
var parts = line.Split('|');
if (parts.Length == 2 && int.TryParse(parts[1], out int qty))
warehouse[parts[0]] = qty;
}
}
}
static void SaveWarehouse()
{
var lines = warehouse.Select(kvp => $"{kvp.Key}|{kvp.Value}").ToArray();
File.WriteAllLines(fileName, lines);
}
static void AddProduct()
{
Console.Write("Название товара: ");
string name = Console.ReadLine();
Console.Write("Количество: ");
if (int.TryParse(Console.ReadLine(), out int qty) && qty > 0)
{
if (warehouse.ContainsKey(name))
warehouse[name] += qty;
else
warehouse[name] = qty;
SaveWarehouse();
Console.WriteLine($"Товар добавлен. Теперь {warehouse[name]} шт.");
}
else
Console.WriteLine("Некорректное количество.");
}
static void SellProduct()
{
Console.Write("Название товара: ");
string name = Console.ReadLine();
if (!warehouse.ContainsKey(name))
{
Console.WriteLine("Товар отсутствует на складе.");
return;
}
Console.Write("Количество для продажи: ");
if (int.TryParse(Console.ReadLine(), out int qty) && qty > 0)
{
if (warehouse[name] >= qty)
{
warehouse[name] -= qty;
if (warehouse[name] == 0)
warehouse.Remove(name);
SaveWarehouse();
Console.WriteLine($"Продано {qty} шт. Осталось {(warehouse.ContainsKey(name) ? warehouse[name] : 0)} шт.");
}
else
Console.WriteLine("Недостаточно товара на складе.");
}
else
Console.WriteLine("Некорректное количество.");
}
static void ShowAllProducts()
{
if (warehouse.Count == 0)
{
Console.WriteLine("Склад пуст.");
return;
}
foreach (var kvp in warehouse)
Console.WriteLine($"{kvp.Key}: {kvp.Value} шт.");
}
}