@PureAngel

Программа не работает так, как должна (ошибки в логике, которые не могу найти)?

Я только начинаю учиться работать с файлами в С++ и столкнулась с проблемой. Ошибок в синтаксисе нет, кампилятор не ругается, так что проблема должна быть в логике, но я её найти не могу.

Программа должна работать так (всё происходит через консоль):
Сперва выводится меню с пунктами
1.Add an employee (пункт добавляет элемент в файл)
2.Print elements (пункт печатает таблицу, заполняя её элементами из файла)
3.Sort elements (сортировка таблицы)
0.Exit (выход из программы)

При выборе первого пункта, виводится еще один выбор, для определения того, как элемент будет добавлен (с клавиатуры или генерироваться рандомно)
Choose a method to add an employee:
1. Add an employee by keyboard.
2. Add an employee randomly.

При выборе одного из пунктов выводится следующий выбор, для выбора места, куда добавляется элемент (в начало файла/таблицы или в конец)
Choose a place to add an employee:
1. Add an employee at the beginning.
2. Add an employee at the end.
После этого выбора должно вновь выводиться начальное меню.

Если в меню выбрать пункт "2.Print elements", должен выводиться еще один выбор (печать одного из элементов по выбору или таблицы полностью).

Если в меню выбрать пункт "3.Sort elements", должен выводиться выбор поля, по которому идет сортировка, а потом ещё один выбор (сортировать по возрастанию или по убыванию).

При выборе "0.Exit" программа закрывается.

В программе несколько файлов. Один для запуска Progect.cpp, один с основным кодом функций Functions.cpp и заголовочный файл Functions.h

Код заголовочного файла:
#pragma once

#include <iostream>
#include <cstdlib>
#include <string>
#include <ctime>
#include <windows.h>
#include <sstream>
#include <iomanip>
#include <cstdio>
#include <fstream>
#include <conio.h>
using namespace std;

const int n = 200;

struct Employee {
    string surname;
    string initials;
    int year_of_birth;
    double salary;
};

void print_menu();
void fill_list_by_yourself();
void fill_list_automaticly();
void print_elements_of_list();
void sort_list();
void go_out();
int switcher();
void menu();


Вот код Progect.cpp:
#include <iostream>
#include "Functions.h"
using namespace std;
int main()
{
	menu();
}


Вот код Functions.cpp:
#include "Functions.h"

Employee* employees = new Employee[n];
string surnames[] = { "Мельник", "Бойко", "Коваленко", "Ткаченко", "Коломиєць" };
int CurPos = 0;

ifstream fileIn;
ofstream fileOut;

void print_menu()
{
    system("ClS");

    cout << "1.Add an employee: " << endl;
    cout << "2.Print elements: " << endl;
    cout << "3.Sort elements: " << endl;
    cout << "0.Exit" << endl;
    cout << "Choose an item from the menu:" << endl;

}

void fill_list_by_yourself()
{
    system("ClS");
    fileOut.open("employee.txt", ofstream::in | ofstream::out | ofstream::app);
    string surname, initials, temp;
    int year_of_birth;
    double salary;
    cout << "Surname: ";
    cin >> surname;
    cout << "Initials: ";
    cin >> initials;
    cout << "Year of birth: ";
    cin >> year_of_birth;
    cout << "Salary: ";
    cin >> salary;
    temp = surname + " " + initials + " " + to_string(year_of_birth) + " " + to_string(salary) + "\n";
    fileOut << temp;
    fileOut.close();
    cout << "Element is successfully added" << endl;
}

void fill_list_automaticly()
{
    int place_choice;
    system("ClS");
    cout << "Choose a place to add an employee:" << endl;
    cout << "1. Add an employee at the beginning." << endl;
    cout << "2. Add an employee at the end." << endl;
    cin >> place_choice;

    if (place_choice == 1) {
        system("ClS");
        srand(static_cast<unsigned int>(time(nullptr)));

        // Generate new employee
        string surname, initials;
        int year_of_birth;
        double salary;
        surname = surnames[rand() % 5];
        char firstLetter = rand() % 25 + 'А';
        char secondLetter = rand() % 25 + 'А';
        initials = string() + firstLetter + "." + secondLetter + ".";
        year_of_birth = rand() % 20 + 1940;
        salary = rand() % 10000 / 100.0;

        // Shift existing employees to the right
        fileIn.open("employee.txt");
        int index = 0;
        while (fileIn >> employees[index + 1].surname >> employees[index + 1].initials >> employees[index + 1].year_of_birth >> employees[index + 1].salary) {
            index++;
        }
        fileIn.close();

        // Add new employee at the beginning of the array
        employees[0].surname = surname;
        employees[0].initials = initials;
        employees[0].year_of_birth = year_of_birth;
        employees[0].salary = salary;

        // Open file for writing
        fileOut.open("employee.txt", ofstream::out);
        if (fileOut.is_open()) {
            // Write all employees to the file
            for (int i = 0; i <= index; i++) {
                string temp = employees[i].surname + " " + employees[i].initials + " " + to_string(employees[i].year_of_birth) + " " + to_string(employees[i].salary) + "\n";
                fileOut << temp;
            }
            fileOut.close();
            cout << "Employee is added successfully" << endl;
        }
        else {
            cout << "Unable to open file for writing." << endl;
        }
    }
    else if (place_choice == 2) {
        system("ClS");
        srand(static_cast<unsigned int>(time(nullptr)));
        fileIn.open("employee.txt");

        // Read existing employees from the file
        int index = 0;
        while (fileIn >> employees[index].surname >> employees[index].initials >> employees[index].year_of_birth >> employees[index].salary) {
            index++;
        }
        fileIn.close();

        // Generate new employee
        string surname, initials;
        int year_of_birth;
        double salary;
        surname = surnames[rand() % 5];
        char firstLetter = rand() % 25 + 'А'; 
        char secondLetter = rand() % 25 + 'А'; 
        initials = string() + firstLetter + "." + secondLetter + ".";
        year_of_birth = rand() % 20 + 1940;
        salary = rand() % 10000 / 100.0;

        // Add new employee at the end of the array
        employees[index].surname = surname;
        employees[index].initials = initials;
        employees[index].year_of_birth = year_of_birth;
        employees[index].salary = salary;

        // Open file for writing
        fileOut.open("employee.txt", ofstream::in | ofstream::out | ofstream::app);
        if (fileOut.is_open()) {
            // Write all employees to the file
            for (int i = 0; i <= index; i++) {
                string temp = employees[i].surname + " " + employees[i].initials + " " + to_string(employees[i].year_of_birth) + " " + to_string(employees[i].salary) + "\n";
                fileOut << temp;
            }
            fileOut.close();
            cout << "Employee is added successfully" << endl;
        }
        else {
            cout << "Unable to open file for writing." << endl;
        }
    }
    else {
        cout << "Invalid choice." << endl;
    }
}


void print_elements_of_list() {
    const int table_width = 80;
    fileIn.open("employee.txt");

    cout << "+";
    for (int i = 0; i < table_width - 2; i++) {
        cout << "-";
    }
    cout << "+" << endl;

    //header of table
    cout << "|Прізвище" << setw(23) << "|Ініціали" << setw(20) << "|Рік народження" << setw(10) << "|Оклад" << setw(15) << "|" << endl;
    
    //line after header
    cout << "+";
    for (int i = 0; i < table_width - 2; i++) {
        cout << "-";
    }
    cout << "+" << endl;

    //from file
    int index = 0;
    while (fileIn >> employees[index].surname >> employees[index].initials >> employees[index].year_of_birth >> employees[index].salary) {
        cout << "|"  << employees[index].surname << setw(18);
        cout << "|" << employees[index].initials << setw(10);
        cout << "|" << employees[index].year_of_birth << setw(15);
        cout << "|" << employees[index].salary << setw(15);
        cout << "|" << endl;
        index++;
    }

    cout << "+";
    for (int i = 0; i < table_width - 2; i++) {
        cout << "-";
    }
    cout << "+" << endl;
    fileIn.close();
}

void sort_list()
{
    int column_choice;
    cout << "Choose a column to sort by:" << endl;
    cout << "1. Surname" << endl;
    cout << "2. Initials" << endl;
    cout << "3. Year of birth" << endl;
    cout << "4. Salary" << endl;
    cin >> column_choice;

    switch (column_choice) {
    case 1:
        break;
    case 2:
        break;
    case 3:
        // Sort by year of birth
        break;
    case 4:
        // Sort by salary
        break;
    default:
        cout << "Invalid option." << endl;
        break;
    }
}

void go_out()
{
    cout << "Exiting program..." << endl;
}

int switcher()
{
    int choice, method_choice;
    cin >> choice;
    switch (choice) {
    case 1:
        system("ClS");
        cout << "Choose a method to add an employee:" << endl;
        cout << "1. Add an employee by keyboard." << endl;
        cout << "2. Add an employee randomly." << endl;
        cin >> method_choice;
        switch (method_choice)
        case 1:
        {
            fill_list_by_yourself();
            break;
        case 2:
            fill_list_automaticly();
            break;
        default:
            break;
        }
    case 2:
        print_elements_of_list();
        system("pause");
        break;
    case 3:
        sort_list();
        break;
    case 0:
        go_out();
        break;
    default:
        cout << "Your choice is uncorrect" << endl;
        system("pause");
    }
    return choice;
}

void menu()
{
    SetConsoleCP(1251);
    SetConsoleOutputCP(1251);
    int choice;
    do {
        print_menu();
        choice = switcher();
    } while (choice != 0);
}
  • Вопрос задан
  • 98 просмотров
Решения вопроса 1
vabka
@vabka
Токсичный шарпист
Ты не сказал, как именно ошибка проявляется, так что сложно сказать.

ошибки в логике, которые не могу найти

Для этого:
1. Рефактори код, чтобы с ним легче было работать.
2. Покрывай код автотестами
3. Тестируй нормально, а не наобум, чтобы понятно было, как проявляется ошибка, какое поведение ты ожидал от программы, а какое фактически произошло.
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы