C++输入循环问题:如何实现无输入或按换行时终止输入
Fixing Your C++ Input Termination Logic
Let's walk through why your current code isn't working, then implement a solution that meets your requirement of stopping when the user enters nothing (just presses Enter) or input ends.
What's Wrong With the Original Code?
cin >> nameskips whitespace automatically: This operator ignores all whitespace characters (spaces, tabs, newlines) and only reads non-whitespace sequences. That means it will never capture a newline character into yournamestring—so yourif(name == '\n')check is both a type mismatch (comparing astd::stringto achar) and functionally useless.- Empty input handling is broken: When the user presses Enter without typing anything,
cin >> namefails to read a valid non-whitespace token, which sets the stream's fail state. This will end your loop, but it's not intentional handling of the "empty input" case you want.
The Corrected Solution
To properly read input lines and stop on an empty line, use std::getline instead. This function reads entire lines (including spaces) and stops at the newline character (which it discards, so we can easily check for empty lines):
#include <iostream> #include <string> int main() { std::string input_line; // Continue reading lines until input ends or we get an empty line while (std::getline(std::cin, input_line)) { if (input_line.empty()) { // User pressed Enter without typing anything—exit the loop break; } // Output the entered content (add std::endl if you want a newline after each output) std::cout << input_line; } std::cout << "Exited"; return 0; }
How This Works
std::getline(std::cin, input_line): Reads every character from the input stream until it hits a newline, storing the result (without the newline) ininput_line.input_line.empty()check: If the user presses Enter without typing any characters,input_linewill be empty, triggering our break to exit the loop.- Stream termination: The loop will also exit if the input stream is closed (e.g., user presses Ctrl+D on Unix/Linux/macOS, or Ctrl+Z on Windows), which handles the "no more input" case.
内容的提问来源于stack exchange,提问作者Badhusha
相关产品推荐
相关产品推荐

