[英]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.我的 C++ 介绍类有一个任务,让用户选择 C、D 或 E 来分别处理支票、存入支票或结束程序。 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.
教授指定,如果用户选择 C 或 D,他希望在同一行中同时接受选择和金额。 For example, if a user wants to deposit a check for $20, they would enter "D 20" in one line.
例如,如果用户想存入一张 20 美元的支票,他们将在一行中输入“D 20”。 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.后面跟着一个switch语句。 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.
代码本身在输入 C 或 D 时可以正常工作,但是当我输入 E 结束程序时,只有在最后添加一个数字才能工作,因为要求输入的行需要一个字符和一个浮点数。 However, in the example output my professor showed, you could just enter E and it would terminate.
但是,在我的教授展示的示例输出中,您只需输入 E 即可终止。 Is there any way around this?
有没有办法解决? How can I set it up so it accepts E differently from C and D?
我如何设置它以使其接受与 C 和 D 不同的 E?
EDIT: Here is the switch statement:编辑:这是 switch 语句:
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.