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

如何在C++中读取含空格整数序列,按回车键切换序列存入数组?

Efficiently Read Multiple Lines of Space-Separated Integers in C++

Hey there! Let's ditch that clunky while(1) loop and get your integer sequences read cleanly and efficiently. The key here is leaning on C++ standard library tools that are optimized exactly for this kind of input handling.

The Better Approach: Use std::getline + std::istringstream

Instead of manually looping and checking for characters, we can read entire lines at once, then parse each line's integers using an in-memory string stream. This cuts down on I/O overhead and uses optimized standard library code for parsing—way more efficient than a manual while(1) setup.

Here's a complete, working example:

#include <iostream>
#include <vector>
#include <sstream>
#include <string>

int main() {
    // Use a vector of vectors to store sequences (dynamic, no fixed size limits)
    std::vector<std::vector<int>> arr;
    std::string line;

    // Read each line until input ends (Ctrl+D on Linux/macOS, Ctrl+Z on Windows)
    while (std::getline(std::cin, line)) {
        std::vector<int> current_sequence;
        std::istringstream line_stream(line);
        int num;

        // Extract all integers from the current line
        while (line_stream >> num) {
            current_sequence.push_back(num);
        }

        // Skip empty lines (remove this if you want to keep empty sequences)
        if (!current_sequence.empty()) {
            arr.push_back(current_sequence);
        }
    }

    // Optional: Verify the result matches your expected output
    for (size_t i = 0; i < arr.size(); ++i) {
        std::cout << "arr[" << i << "] = {";
        for (size_t j = 0; j < arr[i].size(); ++j) {
            if (j > 0) std::cout << ", ";
            std::cout << arr[i][j];
        }
        std::cout << "}\n";
    }

    return 0;
}

Why This Is More Efficient

  • Fewer I/O Operations: std::getline reads an entire line in one go, instead of reading character-by-character like a naive while(1) loop. I/O is one of the slowest parts of any program, so minimizing this is key.
  • Optimized Parsing: std::istringstream uses the same optimized integer parsing logic as std::cin, but operates in memory—way faster than manual string splitting.
  • Cleaner, Maintainable Code: No messy conditionals to check for newlines or end-of-input; the standard library handles all edge cases for you.

Quick Notes

  • Ending Input: After entering your three lines, press Ctrl+D (Linux/macOS) or Ctrl+Z (Windows) to signal end-of-input. This matches your requirement of pressing Enter to switch sequences—each Enter completes a line, and the final input termination ends the loop.
  • Empty Lines: The code skips empty lines (if you accidentally press Enter twice). If you need to keep empty sequences (e.g., an empty line maps to an empty vector), just remove the if (!current_sequence.empty()) check.
  • Dynamic Sizing: Using std::vector means you don't have to predefine the number of sequences or the length of each sequence—perfect for your variable-length input.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:59:20