Есть ли более простой способ зацикливания для проверки ошибок и выхода? (C-струны / массивы символов)

Я писал задание, в котором нам поручено создать программу для корзины покупок, которая отслеживает совокупную цену клиента.

Я не могу использовать строки, глобальные переменные или пользовательские функции
Я строго проинструктирован использовать только символьные массивы и циклы.

В то время как моя программа корзины покупок работает нормально, мне было интересно, есть ли способ упростить мой код? Я чувствую, что был бы оштрафован за чрезмерную сложность кода. Я чувствую, что моя особенность отказа от курения слишком сложна. Есть ли лучший, более простой способ реализовать его без использования строк или функций?

#include <iostream>
#include <iomanip>
#include <cmath>

using namespace std;int main()
{
char continueOrQuit;
char productName[900];
float productPrice;
float totalCost = 0;
int productQuantity = 0;
bool validResponse;

cout << "Welcome to SmartCart" << endl;
cout << "Simply enter the name of your product when prompted" << endl;
cout << "After you enter your product, enter the price when prompted \n\n";

//while ((productName[900] != 'D', 'o', 'n', 'e') || (productName[900] != 'd', 'o', 'n', 'e'))
//While im not done shopping
do
{

cout << "Name of Product: "; // Prompt for product
cin.getline(productName, 900); // Get the name
cout << endl;
cout << "Cost of Product: "; // Prompt for product cost
cin >> productPrice; // Get the cost
while ((!cin) || (productPrice < 0))
{
cout << "Invalid Input!! Try again!!" << endl << endl;
cout << "Cost of Product: "; // Prompt again for product cost
cin.clear();
cin.ignore(100, '\n');
cin >> productPrice;
}
cin.ignore(250, '\n'); // Ignore the rest of the garbage
cout << endl;
// if everything is correct, we set up the display and give the results.

cout.setf(ios::fixed, ios::floatfield);
cout.setf(ios::showpoint);
cout.precision(2);
cout << "The item(s) \"" << productName << "\" has/have been added to your cart for $"<< productPrice << endl;
totalCost = totalCost + productPrice; // Calculating the cumulative sum total
cout << "Your shopping total so far is: $" << totalCost << endl; // Display the sum total
productQuantity++; // Count the number of items in cart
cout << "You have " << productQuantity << " item(s) in your cart." << endl;
// Display the amount of characters in the cart
cout << "To quit shopping, type \"Q\". Otherwise, type \"C\" (Without quotation marks)"<< endl;
cout << "Would you like to continue shopping? (C/Q) : ";
cin >> continueOrQuit;
cin.ignore(100, '\n');
continueOrQuit = tolower(continueOrQuit);
if (continueOrQuit == 'q')
{
cout << "You have chosen to finish and check out." << endl;
validResponse = true;
}
else if (continueOrQuit == 'c')
validResponse = true;
else
cout << "You have to type either C or Q!" << endl;
validResponse = false;
while (!validResponse)
{
cout << "Would you like to continue shopping? (C/Q) : ";
cin >> continueOrQuit;
cin.ignore(100, '\n');
continueOrQuit = tolower(continueOrQuit);

if (continueOrQuit == 'q')
{
cout << "You have chosen to finish and check out." << endl;
validResponse = true;
}
else if (continueOrQuit == 'c')
validResponse = true;
}
} while (continueOrQuit == 'c');

cout << "Your checkout total is $" << totalCost << endl;
cout << "You are purchasing a total of " << productQuantity << endl;
system("PAUSE");
return 0;

} `

-1

Решение

Вот более короткая версия вашего кода.
в основном я удалил лишний код при проверке ввода, поставив do while поэтому в случае неправильного ввода повторного ввода вернитесь к первой попытке.

У вас также есть пропущенная скобка в последнем, это заставляет вас повторно вводить q или c, если вы уже ввели ее правильно.

Вот код, который вы можете сравнить с оригиналом.

int main()
{
char continueOrQuit;
char productName[900];
float productPrice;
float totalCost = 0;
int productQuantity = 0;
bool validResponse;

cout << "Welcome to SmartCart" << endl;
cout << "Simply enter the name of your product when prompted" << endl;
cout << "After you enter your product, enter the price when prompted \n\n";

do
{
cout << "Name of Product: "; // Prompt for product
cin.getline(productName, 900); // Get the name
cout << endl;
do{
cout << "Cost of Product: "; // Prompt for product cost
cin >> productPrice; // Get the cost
if(!cin || productPrice < 0){
cout << "Invalid Input!! Try again!!" << endl << endl;
cin.clear();
cin.ignore(100, '\n');
}
}while ((!cin) || (productPrice < 0));

cin.ignore(250, '\n'); // Ignore the rest of the garbage
cout << endl;
// if everything is correct, we set up the display and give the results.

cout.setf(ios::fixed, ios::floatfield);
cout.setf(ios::showpoint);
cout.precision(2);
cout << "The item(s) \"" << productName << "\" has/have been added to your cart for $"<< productPrice << endl;
totalCost = totalCost + productPrice; // Calculating the cumulative sum total
cout << "Your shopping total so far is: $" << totalCost << endl; // Display the sum total
productQuantity++; // Count the number of items in cart
cout << "You have " << productQuantity << " item(s) in your cart." << endl;
// Display the amount of characters in the cart

do{
cout << "To quit shopping, type \"Q\". Otherwise, type \"C\" (Without quotation marks)"<< endl;
cout << "Would you like to continue shopping? (C/Q) : ";
cin >> continueOrQuit;
cin.ignore(100, '\n');
continueOrQuit = tolower(continueOrQuit);
if(continueOrQuit == 'q' || continueOrQuit == 'c')
validResponse = true;
else
{
cout << "You have to type either C or Q!" << endl;
validResponse = false;
}
}while(!validResponse);
if (continueOrQuit == 'q')
{
cout << "You have chosen to finish and check out." << endl;
}
} while (continueOrQuit == 'c');

cout << "Your checkout total is $" << totalCost << endl;
cout << "You are purchasing a total of " << productQuantity << endl;
system("PAUSE");
return 0;
}
0

Другие решения


По вопросам рекламы ammmcru@yandex.ru
Adblock
detector