简体   繁体   中英

How can I accept user input differently from the same line in C++?

I have an assignment for my intro C++ class to make a program that has a user select C, D, or E to process a check, deposit a check, or end the program respectively. The professor specified that if a user chooses C or D, he would like to accept both the selection and the amount of money in the same line. For example, if a user wants to deposit a check for $20, they would enter "D 20" in one line. I have it set up as such:

cout << "Enter the beginning balance:\n\n";
cin >> balance;

cout << "Commands:\n";
cout << "C - process a check\n";
cout << "D - process a deposit\n";
cout << "E - end the program\n\n";

while (choice != 'E')
{
    cout << "Enter a transaction:\n";
    cin >> choice >> amount;

Followed by a switch statement. The code itself works properly when entering C or D, but when I go to enter E to end the program, it will only work if I add a number to the end, because the line asking for input wants a char and a float. However, in the example output my professor showed, you could just enter E and it would terminate. Is there any way around this? How can I set it up so it accepts E differently from C and D?

EDIT: Here is the switch statement:

switch(choice)
{
    case 'C':cout << fixed << setprecision(2);
             cout << "Processing check for $" << amount << endl;
             balance = processCheck(amount, balance);
             cout << "Balance: $" << balance << endl;
             break;
    case 'D':cout << fixed << setprecision(2);
             cout << "Processing deposit for $" << amount << endl;
             balance = depositCheck(amount, balance);
             cout << "Balance: $" << balance << endl;
             break;
    case 'E':cout << "Processing end of month\n";
             cout << "Final balance: $" << balance << endl;
             break;
    default : cout << "Invalid choice\n";
}

Already answered in comments, but anyway:

Replace this code

cin >> choice >> amount;

by gradual and conditional input code:

cin >> choice;
if (choice == 'C' || choice == 'D')
    cin >> amount;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM