C++交替读取数字与分隔字符直至输入结束的实现问询
Alternately Reading Numbers and Separators in C++ Until Input Ends
Alright, let's tackle this problem step by step. You need to read numbers and their immediately following separator characters alternately until the input ends, and when a newline is encountered as the separator after a number, your program should output a newline and keep processing the rest of the input.
Core Logic Breakdown
- We’ll use a loop that runs as long as we can successfully read an integer from the input stream.
- For each integer we read, we then capture the next character (this could be a space, newline, or even another non-digit character, though your example uses spaces and newlines).
- If the captured separator is a newline character (
'\n'), we’ll trigger a newline in our program before continuing. - We stop the loop when we can’t read any more integers (either because we’ve reached the end of input, or invalid input is encountered).
Complete Code Example
#include <iostream> int main() { int number; char separator; // Start the loop: keep going as long as we can read an integer while (std::cin >> number) { // You can replace this with whatever processing you need for the number std::cout << "Read number: " << number << "\n"; // Read the next character immediately after the number (including spaces/newlines) // Using cin.get() instead of cin >> because cin >> skips whitespace std::cin.get(separator); // Check if the separator is a newline if (separator == '\n') { std::cout << "Encountered newline — continuing on new line\n"; } } std::cout << "Input has ended\n"; return 0; }
Key Details to Note
- Reading Numbers:
std::cin >> numberworks perfectly here because it automatically skips any leading whitespace (like spaces or newlines) to grab the next integer. When there’s no more valid input (EOF), this expression returnsfalseand exits the loop. - Reading Separators: We use
std::cin.get(separator)instead ofstd::cin >> separatorbecause the latter skips whitespace characters. We need to capture every character that comes right after the number—including spaces and newlines—soget()is the right choice here. - Handling Newlines: When we detect a newline as the separator, we can perform any action you need (in the example, we print a message, but you could just output a newline or adjust your processing flow as required).
- Termination: The loop naturally stops when
std::cin >> numberfails, which covers cases like end-of-input or non-numeric input breaking the sequence.
Test with Your Sample Input
If you input:
1 2 34 4 58975 6 2 356 4 5 3 77 5 89 1
The program will output:
Read number: 1 Read number: 2 Read number: 34 Read number: 4 Read number: 58975 Read number: 6 Encountered newline — continuing on new line Read number: 2 Read number: 356 Read number: 4 Read number: 5 Read number: 3 Read number: 77 Read number: 5 Read number: 89 Read number: 1 Input has ended
内容的提问来源于stack exchange,提问作者Amartya Roy
相关产品推荐
相关产品推荐

