![](/img/trans.png)
[英]How can I split string and integer when user input both the string and the integer in the same line in C++?
[英]How can I accept user input differently from the same line in C++?
我的 C++ 介紹類有一個任務,讓用戶選擇 C、D 或 E 來分別處理支票、存入支票或結束程序。 教授指定,如果用戶選擇 C 或 D,他希望在同一行中同時接受選擇和金額。 例如,如果用戶想存入一張 20 美元的支票,他們將在一行中輸入“D 20”。 我是這樣設置的:
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;
后面跟着一個switch語句。 代碼本身在輸入 C 或 D 時可以正常工作,但是當我輸入 E 結束程序時,只有在最后添加一個數字才能工作,因為要求輸入的行需要一個字符和一個浮點數。 但是,在我的教授展示的示例輸出中,您只需輸入 E 即可終止。 有沒有辦法解決? 我如何設置它以使其接受與 C 和 D 不同的 E?
編輯:這是 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";
}
已經在評論中回答了,但無論如何:
替換此代碼
cin >> choice >> amount;
通過漸進和條件輸入代碼:
cin >> choice;
if (choice == 'C' || choice == 'D')
cin >> amount;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.