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

如何提取.txt文件的前三个数值并存储到数组中

提取txt文件首行前三个数值到数组的实现方案

核心实现逻辑统一为:读取文件第一行内容 → 按逗号为分隔符拆分内容 → 取拆分后的前三个元素 → 清除元素前后的多余空格 → 转换为数值类型存入数组

以下为不同常用开发环境的实现代码:

Python 版本

# 替换为你本地实际的txt文件路径
file_path = "your_file.txt"

with open(file_path, "r", encoding="utf-8") as f:
    # 读取首行并去除首尾换行符
    first_line = f.readline().strip()
    # 按逗号拆分、过滤空值、转整数后取前三个存入数组
    res_array = [int(item.strip()) for item in first_line.split(",")[:3]]

# 验证输出
print(res_array) # 输出结果:[8, 8, 27]

C++ 版本

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

int main() {
    // 替换为你本地实际的txt文件路径
    const char* file_path = "your_file.txt";
    std::ifstream in_file(file_path);
    std::vector<int> res_array;
    std::string first_line, temp_str;

    if (std::getline(in_file, first_line)) {
        std::stringstream ss(first_line);
        int count = 0;
        // 按逗号拆分,仅取前三个数值
        while (std::getline(ss, temp_str, ',') && count < 3) {
            // 去除字符串前后的空白字符
            size_t start_pos = temp_str.find_first_not_of(" \t\n\r");
            size_t end_pos = temp_str.find_last_not_of(" \t\n\r");
            int num = std::stoi(temp_str.substr(start_pos, end_pos - start_pos + 1));
            res_array.push_back(num);
            count++;
        }
    }
    // 验证输出
    for (int val : res_array) {
        std::cout << val << " ";
    }
    return 0;
}

Shell 命令行快速实现

# 替换为你本地实际的txt文件路径,直接将结果存入数组arr
arr=($(head -n1 your_file.txt | awk -F', ' '{print $1,$2,$3}'))
# 验证输出
echo ${arr[@]} # 输出结果:8 8 27

如果需求中的数值为浮点类型,仅需要将对应代码中的整数转换逻辑替换为浮点转换即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 00:06:06