如何在用户输入字符并按回车键后关闭程序

How to close the program after the user enters a character and presses the enter key?

本文关键字:回车 关闭程序 字符 用户 输入      更新时间:2023-10-16

我刚开始学习编程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) { } 循环中,以便它不会自动退出。

在程序末尾添加以下行。

系统("暂停");

应用程序来到这一行,它将向您展示

按任意键继续 . . . 消息。单击按钮后,应用程序会自动退出该过程。