You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C++控制台程序中实现回车换行输入与ESC键终止程序的功能?

Fixing Your C++ Console Input Handler

Let's walk through what's wrong with your current code and how to build the functionality you need—allowing Enter to create newlines and ESC to exit the program.

What's Not Working in Your Original Code

  • Your current logic uses getline which reads an entire line at once, so you can't detect the ESC key mid-input (since getline only stops at a newline).
  • The while(cin.get() == '\n') loop runs after getline, which already consumed the newline character—so this loop won't behave as expected.
  • There's no code to check for the ESC key at all.

Correct Implementation

Here's a revised version that handles both Enter and ESC properly, using _getch() from <conio.h> to read individual keystrokes:

#include <iostream>
#include <conio.h>
#include <string>
using namespace std;

int main() {
    string message;
    cout << "Please enter your message (Press Enter for newline, ESC to exit):\n\n";
    cout << "Message: ";

    char ch;
    while (true) {
        ch = _getch(); // Read a single character without echoing it

        // Check for ESC key (ASCII code 27)
        if (ch == 27) {
            cout << "\n\nProgram terminated by ESC key.\n";
            break;
        }

        // Check for Enter key (handles both \r and \n for cross-platform)
        if (ch == '\r' || ch == '\n') {
            cout << '\n'; // Print newline
            message += '\n'; // Add newline to stored message if needed
            // Optional: Reprint "Message: " prompt on new line if desired
            // cout << "Message: ";
        } else {
            cout << ch; // Echo the character to console
            message += ch; // Add character to stored message
        }
    }

    // Optional: Print the full stored message at the end
    // cout << "\n\nYour full message was:\n" << message << endl;
    return 0;
}

Key Explanations

  • _getch(): This function reads a single character from the keyboard without automatically echoing it to the console, which lets us handle special keys like ESC.
  • ESC Detection: The ESC key has an ASCII value of 27—we check for this to break out of the loop and terminate the program.
  • Enter Handling: We check for both '\r' (carriage return, common on Windows) and '\n' (newline, common on Unix-like systems) to ensure cross-platform behavior.
  • Message Storage: We build the message string as the user types, so you can access the full input later if needed.

Notes

  • <conio.h> is a non-standard header—if you're using a compiler like GCC on Linux, you might need to use ncurses instead, but for Windows compilers like MSVC or MinGW, this should work fine.
  • If you want the Enter key to just move to a new line without reprinting the "Message: " prompt, leave the relevant line commented out.

内容的提问来源于stack exchange,提问作者Hassan Afridi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 05:22:30