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

如何按用户输入的数量将对应内容在同一行打印输出

实现单行输入对应数量内容的解决方案

核心逻辑是先读取输入的数量值,再单独读取一行完整输入,按分隔符(通常为空格)拆分后取对应数量的有效值即可,不要循环调用单次输入接口。

常见语言实现示例

Python

n = int(input())
# 读取单行输入,按空格拆分,转成对应类型,取前n个值
nums = list(map(int, input().split()))[:n]
# 输出效果验证
print(' '.join(map(str, nums)))

如果需要限制用户必须输入恰好n个值,可以加校验逻辑:

while True:
    nums = list(map(int, input().split()))
    if len(nums) == n:
        break
    print(f"请输入恰好{n}个数值,用空格分隔")

C++

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

using namespace std;

int main() {
    int n;
    cin >> n;
    // 忽略之前输入n后的换行符,避免getline读空
    cin.ignore();
    
    string line;
    getline(cin, line);
    istringstream iss(line);
    vector<int> nums;
    int num;
    while (iss >> num && nums.size() < n) {
        nums.push_back(num);
    }
    
    // 输出验证
    for (int i = 0; i < nums.size(); i++) {
        if (i > 0) cout << " ";
        cout << nums[i];
    }
    return 0;
}

JavaScript(Node.js环境)

const readline = require('readline');
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

let n;
rl.on('line', (line) => {
    if (n === undefined) {
        n = parseInt(line);
    } else {
        const nums = line.split(' ').map(Number).slice(0, n);
        // 输出验证
        console.log(nums.join(' '));
        rl.close();
    }
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 14:45:00