E
E
Egor Nameles2018-09-11 13:35:46
C++ / C#
Egor Nameles, 2018-09-11 13:35:46

It is impossible to implement in the class of writing and reading to / from a file. What actions do you recommend?

Hello. Wrote a class with deleting, adding and editing lines. I also want to add functions for writing to a file and reading from a file. Can you please tell me how to implement them?
Sport.h file

#pragma once
#include <iostream>
#include <string>
#include <vector>
#include <iomanip>
#include <fstream>

using namespace std;
typedef string str;

class Sport
{
private:
  str Name;
  char Team;
  float Bal;
  int Mesto;
  vector<Sport> SP;
public:
  Sport();
  Sport(str name, char team, float bal, int mesto, vector<Sport> sp);
  void setName(const str&);
  void setTeam(char);
  void setBal(float);
  void setMesto(int);

  const str& getName() const;
  const char getTeam() const;
    const float getBal() const;
  const int getMesto() const;

  void Menu();
  void Show();
  void Add();
  void Del();
  void Remove();
  
  ~Sport();
};

Sport.cpp file
#include "Sport.h"
#include <iostream>
#include <string>
#include <vector>
#include <iomanip>

using namespace std;


Sport::Sport()
{
  Name = "Имя не указано";
  Team = '\0';
  Bal = 0.0;
  Mesto = 0;
}

Sport::~Sport()
{
}

Sport::Sport(str name, char team, float bal, int mesto, vector<Sport> sp)
  : Name(name), Team(team), Bal(bal), Mesto(mesto), SP(sp)
{ }

void Sport::setName(const str& name)
{
  Name = name;
}

void Sport::setTeam(char team)
{
  Team = team;
}

void Sport::setBal(float bal)
{
  Bal = bal;
}

void Sport::setMesto(int mesto)
{
  Mesto = mesto;
}

const str& Sport::getName() const
{
  return Name;
}

const char Sport::getTeam() const
{
  return Team;
}

const float Sport::getBal() const
{
  return Bal;
}

const int Sport::getMesto() const
{
  return Mesto;
}

void Sport::Menu()
{
  cout << "1 - Добавить нового участника\n";
  cout << "2 - Редактировать данные об участнике\n";
  cout << "3 - Удалить участника\n";
  cout << "0 - Выход\n";
}

void Sport::Show()
{
  system("cls");
  cout << "------------------------------------------------------------------------------------------------" << endl;
  cout << "Ведомость спортивних состязаний" << endl;
  cout << "------------------------------------------------------------------------------------------------" << endl;
  cout << "  №" << setw(26) << "Фамилия участника" << setw(20) << "Код команды" << setw(25) << "Количество балов" << setw(20) << "Место в итоге" << endl;
  cout << "------------------------------------------------------------------------------------------------" << endl;
  for (int i = 0; i < SP.size(); i++) {
    cout << "  " << i + 1 << '\t' << setw(15) << SP[i].Name << setw(20) << SP[i].Team << setw(24) << SP[i].Bal << setw(20) << SP[i].Mesto << endl;
    if (i != SP.size() - 1)
    {
      cout << " -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  - " << endl;
    }
  }
  cout << "------------------------------------------------------------------------------------------------" << endl;
  cout << " Примечание: D - Динамо, C - Спартак, S - Шахтер" << endl;
  cout << "------------------------------------------------------------------------------------------------" << endl;
}
void Sport::Add()
{
  int n;
  Sport t;
  SP.push_back(t);
  cout << "Введите фамилию участника: ";
  cin >> SP[SP.size() - 1].Name;
  do {
    n = 0;
    cout << "Введите код команды (D - Динамо, C - Спартак, S - Шахтер):";
    cin >> SP[SP.size() - 1].Team;
    if (SP[SP.size() - 1].Team != 'D' && SP[SP.size() - 1].Team != 'C' && SP[SP.size() - 1].Team != 'S')
    {
      n = 1;
      cout << "Вы ввели некорректный код команды, повторите ввод:\n";
    }
  } while (n == 1);
  n = 0;
  do {
    n = 0;
    cout << "Введите количество балов: ";
    cin >> SP[SP.size() - 1].Bal;

    if (!cin.good() || SP[SP.size() - 1].Bal < 0)
    {
      n = 1;
      cout << "Вы ввели некорректное число, повторите ввод:\n";
    }
  } while (n == 1);
  n = 0;
  do {
    n = 0;
    cout << "Введите итоговое место: ";
    cin >> SP[SP.size() - 1].Mesto;
    if (SP[SP.size() - 1].Mesto < 0)
    {
      n = 1;
      cout << "Вы ввели некорректное число, повторите ввод:\n";
    }
  } while (n == 1);
  n = 0;
  Show();
}
void Sport::Del()
{
  int n;
  cout << "Введите номер строки, которую Вы желаете удалить: ";
  cin >> n;
  SP.erase(SP.begin() + n - 1);
  Show();
}
void Sport::Remove()
{
  int p;
  int n;
  cout << "Введите номер строки, которую Вы хотите отредактировать: ";
  cin >> n;
  cout << "Введите фамилию участника: ";
  cin >> SP[n - 1].Name;
  do {
    p = 0;
    cout << "Введите код команды (D - Динамо, C - Спартак, S - Шахтер)::";
    cin >> SP[SP.size() - 1].Team;
    if (SP[SP.size() - 1].Team != 'D' && SP[SP.size() - 1].Team != 'C' && SP[SP.size() - 1].Team != 'S') {
      n = 1;
      cout << "Вы ввели некорректный код команды, повторите ввод:\n";
    }
  } while (p == 1);
  p = 0;
  do {
    p = 0;
    cout << "Введите количество балов: ";
    cin >> SP[SP.size() - 1].Bal;
    if (SP[SP.size() - 1].Bal < 0)
    {
      p = 1;
      cout << "Вы ввели некорректное число, повторите ввод:\n";
    }
  } while (p == 1);
  p = 0;
  do {
    p = 0;
    cout << "Введите итоговое место: ";
    cin >> SP[SP.size() - 1].Mesto;
    if (SP[SP.size() - 1].Mesto < 0)
    {
      p = 1;
      cout << "Вы ввели некорректное число, повторите ввод:\n";
    }
  } while (p == 1);
  p = 0;
  Show();
}

main.cpp file
#include "Sport.h"
#include <iostream>
#include <conio.h>
#include <string>
#include <vector>

using namespace std;


int main() {
  setlocale(LC_ALL, "Russian");
  int c;
  Sport B;

  do {
    B.Menu();
    cout << "Ваш выбор: ";
    cin >> c;
    switch (c) {
    case 1:
      B.Add();
      break;
    case 2:
      B.Remove();
      break;
    case 3:
      B.Del();
      break;
    case 0:
      break;
    default: cout << "Некорректный вариант выбора!" << endl;
    }
  } while (c != 0);

  _getch();
  return 0;
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Roman, 2018-09-11
@EgaNator

Tyts
#include <iostream>
#include <string>
#include <vector>
#include <fstream>

using std::ofstream;
using std::vector;
using std::string;
using std::cout;
using std::cin;
using std::endl;

class Sport
{
  vector<Sport> Sp;
  char     team;
  double   bal;
  unsigned mesto;
  string   name;
public:
  Sport(string   _name  = {}, char _team = {}, double _bal = {},
        unsigned _mesto = {}, vector<Sport> sp = {})
      : name {_name}, team{_team}, bal{_bal},
        mesto{_mesto},  Sp{sp} {}

private:
  friend ofstream& operator<<(ofstream& ofs, Sport& sp);
};

ofstream& operator<<(ofstream& ofs, Sport& sp)
{
  ofs << sp.name  << ' ';
  ofs << sp.team  << ' ';
  ofs << sp.mesto << ' ';
  ofs << sp.bal   << ' ';
  ofs << endl;
  for(auto& p : sp.Sp)
  {
    ofs << p;
  }
  return ofs;
}

void writeSportsTo(const char* filename, Sport& sp)
{
  ofstream of(filename);
  if(of)
  {
    of << sp;
    of.close();
  }
}

int main()
{
    constexpr char* filename = "C:\\sports.txt";
    Sport sp;
    writeSportsTo(filename, sp);
    return 0;
}

Чтение аналогично.

F
Fat Lorrie, 2018-09-11
@Free_ze

The way you wrote in the comments - it won't work for complex objects, like Sport.
First, you write and read a binary txt file. Do you have any idea what a file containing data of your type should look like?
Secondly, you have dynamic members inside the object (capable of changing their sizes) - vectorand string. Thanks to this, the object has a multidimensional representation in memory, and you need to figure out how to project it onto a "flat" memory, write it term by term. If with char, int, floateverything is obvious (their sizes are known at the compilation stage: sizeof(char), sizeof(int), sizeof(float)), then forstring, for example, you must first save its size (so that you later know how much to read from the file), and then write the contents. C vector- similar, except that this is the same Sport and you need to call the save function for each child of the current object (and for their children, i.e. traverse the ownership tree recursively).
Reading is done in reverse order.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question