Я пишу программу, в которую я ввожу текстовый файл, в котором есть опции для автомобиля вместе с их ценами в программу. Пользователь выбирает вариант из меню и выбирает модель автомобиля. Цена обновляется, и затем пользователь может выбирать варианты. Параметры и общая цена обновляются в векторах.
У меня проблемы с обновлением цены и добавленных опций. Я добавляю названия опций, но опции или цена не обновляются.
Я знаю, что структуры могли бы быть проще, но мне нужно сделать эту программу, используя векторы.
Вот мой код:
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <iomanip>
#include <cctype>
using namespace std;
//function signature
void showMenu();
void printOptions();
char getModel();
void displaySelection(char model, double totalCost, vector<string> &options);
bool isEqual(string str1, string str2);
void addOption (char model, double &totalCost, vector <double> &price, vector <string> &optionsSelected, vector <string> &optionsAvailable);
void removeOption (char model, double totalCost, vector <double> price, vector <string> optionsSelected, vector <string> optionsAvailable);
// main function to run the program
int main(int argc, char const *argv[])
{
// print a welcome message
cout << "Bobcats Auto Dealership" << endl;
// declare variables
int menuChoice;
char model = ' ';
double totalCost = 0;
vector<double> price;
vector<string> optionsAvailable;
vector<string> optionsSelected;
// read input from file
ifstream inStream("options.txt");
if (inStream.fail())
{
cout << "Error Opening File" << endl;
exit (0);
}
while (!inStream.eof())
{
// first input is price of option
int cost;
inStream >> cost; // get price of option
// rest of line is option details
string option;
getline(inStream, option);
// add price to price list
price.push_back(cost);
// add option
if (option[0] == ' ')
{
option = option.substr(1, option.length() - 1); // ignore white space at start of option name
}
optionsAvailable.push_back(option);
}
// show menu and ask for option till user select quit
while (menuChoice != 6)
{
cout << endl; // print empty line
// display user selected option
displaySelection(model, totalCost, optionsSelected);
// show menu for next selection
showMenu();
cin >> menuChoice; // get user input
// check for valid input
if (menuChoice < 0 || menuChoice>6)
{
cout << "Invalid menu choice" << endl;
}
if (menuChoice ==1)
{
if (model == ' ')
{
model = getModel();
// check the model and add cost
if (model == 'E') {
totalCost = 10000.0;
}
else if (model == 'L') {
totalCost = 12000.0;
}
else {
// model is X
totalCost = 18000.0;
}
}
}
else if (menuChoice ==2)
{
printOptions();
}
else if (menuChoice == 3 )
{
addOption(model, totalCost, price, optionsSelected, optionsAvailable);
/** if (model != ' ')
{
cout << "Enter option: ";
string option_name;
cin.ignore(); // ignore newline character
getline(cin, option_name); // get option name from user
// check if option is available
for (size_t i = 0; i < optionsAvailable.size(); i++) {
if (isEqual(optionsAvailable.at(i),option_name)) {
// check if user already selected that option
bool isSelected = false;
for (size_t j = 0; j < optionsSelected.size(); j++) {
if (isEqual(optionsSelected.at(i),optionsSelected.at(j))) {
isSelected = true; // set flag to true
}
}
// add option to selected option if not already selected
if (!isSelected) {
optionsSelected.push_back(optionsAvailable.at(i));
// add cost of option
totalCost = totalCost + price.at(i);
}
}
}
}
*/
}
else if (menuChoice ==4 )
{
removeOption ( model, totalCost, price, optionsSelected, optionsAvailable);
/**if (model != ' ') {
cout << "Enter option: ";
string option_name;
cin.ignore(); // ignore newline character
getline(cin, option_name); // get option name from user
// check if option is seleced
for (size_t i = 0; i < optionsSelected.size(); i++) {
if (isEqual(optionsSelected.at(i),option_name)) {
// remove cost of option
for (size_t j = 0; j < optionsAvailable.size(); j++) {
if (isEqual(optionsSelected.at(i), optionsAvailable.at(j))) {
totalCost = totalCost - price.at(j);
}
}
// remove option from selected option
optionsSelected.erase(optionsSelected.begin() + i);
}
}
}
*/
}
else if (menuChoice ==5)
{
// cancel order and start new one
model = ' ';
totalCost = 0;
optionsSelected.clear();
}
}
while (menuChoice != 6);
return 0;
}
// function implementaion
void displaySelection(char model,double totalCost, vector<string> &options)
{
// check if order is started
if (model == ' ') {
cout << "NO MODEL SELECTED" << endl;
}
else {
// print model
cout << "Model: " << model << ", $" << fixed << setprecision(2) << totalCost << endl;
cout << "Options: ";
// check for options
if (options.size() > 0) {
// print all options
for (size_t i = 0; i < options.size(); i++)
{
// print 3 options per line
if (i != 0 && i % 3 == 0)
{
cout << endl;
}
// print each option
cout << options.at(i);
// add commas
if (i < options.size() - 1) {
cout << ", ";
}
}
}
else {
cout << "None";
}
cout << endl; // print newline
}
}
void showMenu()
{
cout << "1. Select a model(E, L, X)" << endl;
cout << "2. Display available options and prices" << endl;
cout << "3. Add an option" << endl;
cout << "4. Remove an option" << endl;
cout << "5. Cancel order" << endl;
cout << "6. Quit" << endl;
cout << "Enter choice: " << endl;
}
void printOptions()
{
cout << " " << endl;
cout << "Prices for model E, L, & X: $10,000, $12,000, $18,000" << endl;
cout << "Available Options" <<endl;
cout << "" << endl;
cout << "Leather Seats ($5000) Dvd System ($1000) 10 Speakers" << endl;
cout << "Navigation System ($1400) CarPlay ($500) Android Auto ($500)" << endl;
cout << "Lane Monitoring ($2000) 3/36 Warranty ($800) 6/72 Warranty ($999)" << endl;
cout << "Dual Climate ($1500) Body Side Molding ($225) Cargo Net ($49)" << endl;
cout << "Cargo Organizer ($87) 450W Audio ($700) Heated Seats ($1000)" << endl;
}
char getModel()
{
string model = "S";
cin.ignore(); // ignore newline character
// promt user for model till valid model is selected
while (true) {
cout << "Enter the model (E, L, X): ";
getline(cin, model);
// check for valid model
if (model.length() == 1) {
char c = toupper(model[0]);
if (c=='E' || c=='L' || c=='X') {
model = "";
model = model + c;
break;
}
}
}
return model[0];
}
bool compareChar(char& c1, char& c2) {
if (toupper(c1) == toupper(c2)) {
return true;
}
else {
return false;
}
}
bool isEqual(string str1, string str2)
{
return (str1.size() == str2.size() && equal(str1.begin(), str1.end(), str2.begin(), &compareChar));
}
void addOption (char model, double &totalCost, vector <double> &price, vector <string> &optionsSelected, vector <string> &optionsAvailable)
{
if (model != ' ')
{
cout << "Enter option: ";
string option_name;
cin.ignore(); // ignore newline character
getline(cin, option_name); // get option name from user
// check if option is available
for (size_t i = 0; i < optionsAvailable.size(); i++)
{
if (isEqual(optionsAvailable.at(i),option_name)) {
// check if user already selected that option
bool isSelected = false;
for (size_t j = 0; j < optionsSelected.size(); j++)
{
if (isEqual(optionsSelected.at(i),optionsSelected.at(j)))
{
isSelected = true; // set flag to true
}
}
// add option to selected option if not already selected
if (!isSelected)
{
optionsSelected.push_back(optionsAvailable.at(i));
// add cost of option
totalCost = totalCost + price.at(i);
}
}
}
}
}
void removeOption (char model, double totalCost, vector <double> price, vector <string> optionsSelected, vector <string> optionsAvailable)
{
if (model != ' ')
{
cout << "Enter option: ";
string option_name;
cin.ignore(); // ignore newline character
getline(cin, option_name); // get option name from user
// check if option is seleced
for (size_t i = 0; i < optionsSelected.size(); i++)
{
if (isEqual(optionsSelected.at(i),option_name))
{
// remove cost of option
for (size_t j = 0; j < optionsAvailable.size(); j++)
{
if (isEqual(optionsSelected.at(i), optionsAvailable.at(j))) {
totalCost = totalCost - price.at(j);
}
}
// remove option from selected option
optionsSelected.erase(optionsSelected.begin() + i);
}
}
}
}
редактировать: Вот что в файле options.txt: 5000.0 Кожаные сиденья 1000.0 DVD-система 800.0 10 динамиков 1400.0 Навигационная система 500.0 CarPlay 500.0 Android Auto 2000.0 Контроль полосы движения 800,0 3/36 Гарантия 999,0 6/72 Гарантия 1500,0 Dual Climate 225,0 Боковые молдинги кузова 49,0 Автомобиль go Net 87,0 Автомобиль go Органайзер 700,0 450 Вт Аудио 1000,0 Сиденья с подогревом