You need to enable JavaScript to run this app. 如何逐行读取用户输入并将每行存储至数组对应索引位置
优惠活动
大模型
产品
解决方案
定价
更多

如何逐行读取用户输入并将每行存储至数组对应索引位置

逐行读取输入整行存入数组的实现方案

需求匹配说明

完全按照要求把每一行输入保留原始格式、不拆分逗号分隔的内容作为独立元素存入数组,对应存储效果如下:

索引0:Apples raw, 110, 50.6, 1.2, 1.0
索引1:Bananas, 225, 186, 6.2, 8.2
索引2:Bread pita whole wheat, 64, 134, 14, 22.6
索引3:Broccoli raw, 91, 21.9, 2.8, 6.3
索引4:Carrots raw, 128, 46.6, 2.6, 3.3

常用语言实现

C语言(对应原生字符数组场景)

C语言中一般用二维字符数组实现多行存储,代码如下:

#include <stdio.h>
#include <string.h>

#define MAX_STORE_LINES 100   // 最大支持存储的行数
#define MAX_LINE_LENGTH 256   // 单行最大存储字符数

int main() {
    // 定义二维字符数组,每一行对应一个字符数组空间
    char line_storage[MAX_STORE_LINES][MAX_LINE_LENGTH];
    int current_line = 0;

    // 逐行从标准输入读取,直到触发EOF结束输入
    while (current_line < MAX_STORE_LINES 
        && fgets(line_storage[current_line], MAX_LINE_LENGTH, stdin) != NULL) {
        // 移除fgets自带读取的行尾换行符,保留原输入内容
        line_storage[current_line][strcspn(line_storage[current_line], "\n")] = '\0';
        current_line++;
    }

    // 验证存储结果
    for (int i = 0; i < current_line; i++) {
        printf("数组索引%d存储内容:%s\n", i, line_storage[i]);
    }
    return 0;
}

实现注意事项:

  • 必须使用fgets读取,禁止使用已废弃的gets防止缓冲区溢出
  • 提前定义容量上限,避免越界访问
  • 不需要保留换行符的话就用上面的截断逻辑,要保留的话可以删掉那行截断代码

Python实现

Python用列表作为动态数组存储逐行读取的内容:

line_array = []
# 持续读取输入直到结束
while True:
    try:
        current_line = input()
        line_array.append(current_line)
    except EOFError:
        break

# 验证结果
for index, content in enumerate(line_array):
    print(f"数组索引{index}存储内容:{content}")

说明:Python内置的input()方法会自动移除行尾换行符,刚好匹配整行存储的需求。

Java实现

Java用动态集合存储逐行读取的字符串:

import java.util.ArrayList;
import java.util.Scanner;

public class ReadLineToArray {
    public static void main(String[] args) {
        ArrayList<String> lineArray = new ArrayList<>();
        Scanner sc = new Scanner(System.in);

        // 逐行读取直到没有更多输入
        while (sc.hasNextLine()) {
            lineArray.add(sc.nextLine());
        }
        sc.close();

        // 验证结果
        for (int i = 0; i < lineArray.size(); i++) {
            System.out.printf("数组索引%d存储内容:%s%n", i, lineArray.get(i));
        }
    }
}

常见误区规避

  • 不要使用按空格、逗号分隔的读取逻辑,那样会把整行拆成零散字段,不符合“整行存入单个数组元素”的要求
  • 读取后记得处理行尾自带的换行符,避免存储内容混入多余的控制字符
  • 处理行数不确定的输入时,要设置合理的容量上限,防止无限制占用内存

内容的提问来源于stack exchange,提问作者Francisco Gutierrez Ramirez

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.13 22:36:03