У меня вопрос, который должен быть простым, но я не могу найти ответ нигде.
У меня есть программа с управляемым меню C++, которая отлично работает, когда параметры меню являются номерами, но я не могу понять, как изменить числа на буквы.
Например:
работает отлично, когда выбор 1, 2 или 3, но не A, B, C.
Не уверен, как я должен объявить вариант... это символ? заранее спасибо
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
//Variables needed for the problem
int numbServCharge; //number of service charges
char choice; //menu choice
double transAmt, balence, totalServCharge; //transaction amount, current balence, total service charges
//Constant service change
const double servCharge = 0.25; //constant $0.25 for service charges
numbServCharge = 0; //Start the counter for number of service charges at zero
cout << "Checkbook Balencing Program\n\n";
cout << "Enter the beginning balence: ";
cin >> balence; //get the initial balence
cout << endl;
do
{
//Highlight menu options
cout << "\nCommands\n";
cout << "C - process a check\n";
cout << "D - process a deposit\n";
cout << "E - end the program\n\n";
//Get user choice from menu
cout << "Enter transaction type: ";
cin >> choice;
cout << endl;
//Create an error message for invalid choice and get a second choice
while((choice != 'C') && (choice != 'D') && (choice != 'E')
{
cout << "Invalid selection. Please choose C, D or E: ";
cin >> choice;
}
//Set up for option #1 -- using a check
if(choice=='C')
{
cout << "Enter transaction amount: ";
cin >> transAmt; //Get the amount of the check
cout << "\nProcessing check for $" << fixed << setprecision(2) << transAmt;
transAmt = transAmt + servCharge; //Add the service charge onto the transaction
numbServCharge++; //Add one to the number of service charges there have been
balence = balence - transAmt; //Update account balence
cout << "\nBalence: $" << fixed << setprecision(2) << balence;
cout << "\nService charge: $0.25 for a check\n";
totalServCharge = servCharge * numbServCharge; //Update total cost of service charges
cout << "Total service charges: $" << fixed << setprecision(2) << totalServCharge << endl; //Tell user total service charges so far
}
//Set up for option #2 -- deposits
if(choice=='D')
{
cout << "Enter transaction amout: ";
cin >> transAmt; //Get the amount of the deposit
cout << "\nProcessing Deposit for $" << fixed << setprecision(2) << transAmt << endl;
transAmt = transAmt - servCharge; //Add the service charge onto the deposit
numbServCharge++; //Add one to the number of service charges there have been
balence = balence + transAmt; //Update account balence
cout << "Balence: $" << fixed << setprecision(2) << balence << endl;
totalServCharge = servCharge * numbServCharge; //Update total cost of service charges
cout << "Total service charges: $" << fixed << setprecision(2) << totalServCharge << endl; //Tell user total service charges so far
}
}while(choice != 'E'); //Close program if option 3 is selected
//Display final balence
cout << "Processing end of the month";
cout << "\nFinal balence : $ " << fixed << setprecision(2) << balence << endl << endl;
system("pause"); //Pause screen so it doesn't close right away
return 0;
}
При тестировании строки вы должны преобразовать все в обычный случай. В этом случае вы должны преобразовать пользовательский ввод в верхний регистр. Вы можете сделать это, используя функцию toupper
Вот немного кода, который вам нужно изменить, чтобы ваша программа работала
cout << "Enter transaction type: ";
cin >> choice;
choice = toupper(choice); // Change Here
cout << endl;
Когда вы меняете в while((choice != 'C') && (choice != 'D') && (choice != 'E')
до while((choice != 'C') && (choice != 'D') && (choice != 'E'))
, ваш код работает хорошо. Хотя я бы лично использовал std::string
вместо char
.
Конечно, ответ Цезаря - действительный момент - и я тоже изменил бы это. Тем не менее, это было бы лучше как комментарий, потому что это не решает проблему. Сейчас подожди. Какая проблема? Ваша программа по-прежнему "отлично работает" даже с вариантами алфавитного меню.
Единственная ошибка в вашей программе - это когда вы пытаетесь назначить balence
(или любую из трех double
с) на нечисловую запись. Когда я набираю "С" для начального баланса, я вижу это чудовище:
Снова и снова и снова. Это не весело. Аналогичная ситуация возникает, если я набираю письмо для суммы транзакции:
Решение. Никогда не пытайтесь замять ввод, полученный непосредственно от пользователя, в переменную, которая не является типом строки. Используйте встроенную функцию string-to-number, например atof
, или (очень предпочтительную) добавьте обработчики ошибок, например:
if (std::cin >> dbl)
{
//input is a double. handle that here.
}
else
{
//input isn't a double. handle that here.
}
Кстати, это означало баланс, а не баланс.)