如何在用户输入字符并按回车键后关闭程序
How to close the program after the user enters a character and presses the enter key?
我刚开始学习编程C++。我的程序运行良好,但我也需要在用户输入字符并按回车键时关闭它。我不知道应该如何做到这一点。任何帮助将不胜感激。到目前为止,我的代码是(运行良好):
#include <iostream>
using namespace std;
int main()
{
int money_spent, money_tendered;
cout << "Enter the total amount spent: n";
cin >> money_spent;
cout << "Enter the amount tendered: n";
cin >> money_tendered;
int balance = money_tendered - money_spent;
int ten_bills = balance / 1000;
balance = balance % 1000;
int five_bills = balance / 500;
balance = balance % 500;
int dollar_coins = balance / 100;
balance = balance % 100;
int quater_coins = balance / 25;
balance = balance % 25;
int dimes = balance / 10;
balance = balance % 10;
int nickels = balance / 5;
balance = balance % 5;
int pennies = balance;
cout << " n n"
<< "Your change is: n"
<< ten_bills << " tenn dollar bill(s). n"
<< five_bills << " five dollar bill(s). n"
<< dollar_coins << " one dollar coin(s). n"
<< quater_coins << " quater(s). n"
<< dimes << " dime(s). n"
<< nickels << " nickel(s). n"
<< pennies << " pennie(s). n";
return 0;
}
添加
cin.ignore();
cin.get();
以前
return 0;
您需要cin.ignore()
,才能忽略输入 money_tendered
后键入的 ENTER。否则,此 ENTER 将被cin.get()
捕获,而不是您要输入的最后一个字符。
使用
getchar();
这是一个标准的 c 函数。
您需要更改 cin 才能读取字符串。 然后,您需要检查该字符串是否为"s"。 如果是这样,则要返回 0。 否则,您希望将字符串转换为整数并将其存储在money_spent或money_tendered中。 然后,您希望将整个过程包装在 while(1) { } 循环中,以便它不会自动退出。
在程序末尾添加以下行。
系统("暂停");
应用程序来到这一行,它将向您展示
按任意键继续 . . . 消息。单击按钮后,应用程序会自动退出该过程。
相关文章:
- 如何在 qt 中从另一个线程运行 qt并发时关闭程序
- 如何在程序崩溃时关闭程序,没有任何警告屏幕等.C++窗口
- QT-从QDialog(MainWindow满载之前)关闭程序
- Gtkmm 3/C++,使用按钮而不是窗口关闭程序"X"
- c ++ Win32 API GetMessage 关闭程序在线程内
- nofify_all()关闭程序时会崩溃
- 每项分辨率的自动关闭程序
- Windows上的C 在启动后立即关闭程序
- 在QT中关闭程序之前,请显示对话框
- 用x关闭程序时内存泄漏
- 在不关闭程序的情况下写入文件后,从文件中获取保存的数据
- Qt:关闭模式对话框关闭程序
- 如何在用户输入字符并按回车键后关闭程序
- 视觉C++ - 在我关闭程序之前,ofstream 不会输出到文件
- C 使用 Y/N 选项循环开关。选择 N 不会关闭程序
- C++关闭程序的方法
- 防止Ctrl-C关闭程序
- 使'Q'关闭程序
- 在我关闭程序之前,对象尚未被处理
- 如何在C++中正确关闭程序