Cześć, zacząłem się trochę bawić c++, a wcześniej nie miałem styczności z programowaniem. Zrobiłem prosty program, można powiedzieć taką mała mini bazę danych, która pozwala na zapisywanie i odczytywanie informacji o samochodach. Program pozwala użytkownikowi dodać informacje o aucie tzn. model, markę, rok produkcji i przebieg i później ją odczytać. Jeśli zamknie program i później go otworzy, to nadal będzie miał dostęp do poprzednio dodanych aut. Czego powinienem unikać w kodzie i co mogę w nim poprawić, bo jestem pewien, że jest tego sporo :D
#include "pch.h"
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
using namespace std;
class car // creat a class
{
private: // variables in class
string brand;
string model;
int pdate;
float car_milea;
public: // methods
car(string brand = "empty", string model = "empty", int pdate = 0, float car_milea = 0) // method of adding new car
{
this->brand = brand;
this->model = model;
this->pdate = pdate;
this->car_milea = car_milea;
}
void c_pok() // shows information about car
{
cout << "The " << brand << " " << model << " was produced in " << pdate << " and has " << car_milea << "km mileage \n";
}
};
vector<car> c_vector; // vector to keep data
int main()
{
string model, brand; // variables
int pdate;
float car_milea;
fstream data; // creat file to save and read
data.open("cardata.txt", std::ios::in);
if (data.good() == false)
cout << "Something went wrong!";
else // read input if exists
{
string line;
int nr_of_line = 1;
while (getline(data, line))
{
switch (nr_of_line)
{
case 1:
brand = line; break;
case 2: model = line; break;
case 3: pdate = atoi(line.c_str()); break;
case 4: car_milea = atof(line.c_str()); break;
}
if (nr_of_line == 4)
{
c_vector.resize(c_vector.size() + 1);
c_vector.push_back(car(brand, model, pdate, car_milea));
nr_of_line = 0;
}
nr_of_line++;
}
data.close();
}
data.open("cardata.txt", std::ios::out | std::ios::app);
if (data.good() == false)
cout << "Something went wrong!";
else
{
while (true) // main func
{
int n;
cout << "Add new car - 1" << endl; // add new car
cout << "List of cars - 2" << endl; // shows list of cars
cout << "Exit - 3" << endl; // exit the program
cin >> n;
if (n > 3)continue;
if (n == 1) // option nr 1
{
c_vector.resize(c_vector.size() + 1);
cout << "Its brand: "; cin >> brand; data << brand << endl;
cout << "Its model: "; cin >> model; data << model << endl;
cout << "Its production year: "; cin >> pdate; data << pdate << endl;
cout << "Its mileage "; cin >> car_milea; data << car_milea << endl;
c_vector.push_back(car(brand, model, pdate, car_milea));
}
if (n == 2) // option 2
{
int p = c_vector.size();
for (int w = 1; w < p; w = w + 2)
{
c_vector[w].c_pok();
cout << endl;
}
}
if (n == 3) // option 3
break;
}
data.close();
}
}
Z góry dzięki!