Advertisement
mikronik24

Untitled

Jun 8th, 2023
858
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.61 KB | None | 0 0
  1. #include <iostream>
  2. #include "fstream"
  3. #include "sstream"
  4. using namespace std;
  5.  
  6. struct car {
  7.     char* name;
  8.     float price;
  9.     int year;
  10. };
  11.  
  12. string * split_car_data(string line){
  13.     string arr[3];
  14.     auto i = 0;
  15.     stringstream ssin(line);
  16.     while (ssin.good() && i < 4){
  17.         ssin >> arr[i];
  18.         ++i;
  19.     }
  20.     return arr;
  21. }
  22.  
  23. int main() {
  24.     fstream file;
  25.     vector<car> cars;
  26.     vector <string> lines;
  27.     string line;
  28.     auto file_path = "/Users/toczekmj/CLionProjects/testy/pojazdy.txt";
  29.     auto changes = false;
  30.  
  31.  
  32.     file.open(file_path);
  33.     if(file.is_open())
  34.     {
  35.         while(getline(file, line))
  36.         {
  37.             auto data = split_car_data(line);
  38.             auto name = data[0];
  39.             auto year = stoi((string)data[1]);
  40.             auto price = stof((string)data[2]);
  41.             char * n_name = new char[name.length()+1];
  42.             std::strcpy(n_name, name.c_str());
  43.  
  44.             if(year >= 2016 && year <= 2021){
  45.                 price -= (price/10);
  46.                 changes = true;
  47.             }
  48.             cars.push_back(
  49.                     car{
  50.                         n_name,
  51.                         price,
  52.                         year
  53.                     }
  54.             );
  55.         }
  56.         file.close();
  57.     }
  58.  
  59.     if(changes){
  60.         file.open(file_path, fstream::out | fstream::trunc);
  61.         if(file.is_open())
  62.         {
  63.             for_each(cars.begin(), cars.end(), [&](const car &item) {
  64.                file << item.name << " " << item.year << " " << item.price << "\n";
  65.             });
  66.         }
  67.     }
  68.     return 0;
  69. }
  70.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement