Untitled
unknown
plain_text
a year ago
3.3 kB
6
Indexable
#include <iostream>
#include <string>
#include <iomanip>
class Car {
private:
std::string brand;
std::string model;
int year;
double price;
double fuelLevel;
public:
// Constructors
Car() : brand("Unknown"), model("Unknown"), year(0), price(0.0), fuelLevel(0.0) {}
Car(std::string brand, std::string model, int year, double price, double fuelLevel)
: brand(brand), model(model), year(year), price(price), fuelLevel(fuelLevel) {}
// Getters and Setters
void setBrand(const std::string& brand) { this->brand = brand; }
void setModel(const std::string& model) { this->model = model; }
void setYear(int year) { this->year = year; }
void setPrice(double price) { this->price = price; }
void setFuelLevel(double fuelLevel) { this->fuelLevel = fuelLevel; }
std::string getBrand() const { return brand; }
std::string getModel() const { return model; }
int getYear() const { return year; }
double getPrice() const { return price; }
double getFuelLevel() const { return fuelLevel; }
// Show values vertically
void showValues() const {
std::cout << "Car Details (Vertical):\n"
<< "Brand: " << brand << "\n"
<< "Model: " << model << "\n"
<< "Year: " << year << "\n"
<< "Price: $" << price << "\n"
<< "Fuel Level: " << fuelLevel << " liters\n";
}
// Show values horizontally
void detailLine() const {
std::cout << "Car Details (Horizontal): "
<< "Brand: " << brand << ", "
<< "Model: " << model << ", "
<< "Year: " << year << ", "
<< "Price: $" << price << ", "
<< "Fuel Level: " << fuelLevel << " liters\n";
}
// Get values interactively
void getValues() {
std::cout << "Enter car details:\n";
std::cout << "Brand: "; std::getline(std::cin, brand);
std::cout << "Model: "; std::getline(std::cin, model);
std::cout << "Year: "; std::cin >> year;
std::cout << "Price: $"; std::cin >> price;
std::cout << "Fuel Level (liters): "; std::cin >> fuelLevel;
std::cin.ignore(); // Clear the input buffer
}
// Additional methods
void drive(double distance) {
double fuelConsumed = distance * 0.1; // Assume 0.1 liters per km
fuelLevel -= fuelConsumed;
if (fuelLevel < 0) fuelLevel = 0; // Prevent negative fuel
std::cout << "Driven " << distance << " km. Fuel remaining: " << fuelLevel << " liters.\n";
}
void refill(double amount) {
fuelLevel += amount;
std::cout << "Refilled " << amount << " liters. Total fuel: " << fuelLevel << " liters.\n";
}
};
int main() {
// Create a Car object using the default constructor
Car car1;
car1.getValues(); // Interactive input
// Display values in both formats
car1.showValues();
car1.detailLine();
// Perform operations (drive and refill)
car1.drive(50); // Drive 50 km
car1.refill(20); // Refill 20 liters of fuel
car1.detailLine();
// Create another Car object using the parameterized constructor
Car car2("Tesla", "Model S", 2023, 79999.99, 100);
car2.showValues();
car2.detailLine();
return 0;
}
Editor is loading...
Leave a Comment