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

实验室作业:如何从文件中拆分多类型数据至对应变量

实验室作业:文件数据拆分与类型转换

你需要从文件中提取并拆分以下字段到对应类型的变量中:

  • 派对ID(整数类型)
  • 餐费(整数类型)
  • 派对中的成人/儿童数量(整数类型)
  • 是否为周末用餐(布尔类型,Y对应True,N对应False)
  • 总账单金额(浮点类型)

数据文件内容

1 10  0 S Y 100.00 
2 27 3 D Y 57.50 
3 125 17 D N 0.00 
4 4 0 S N 25.00 
5 0  25 S Y 23.75 
6 250 43 D N 500.00 
7 0 0 D N 0.0 
8 10 0 R Y 10.00 
9 17 3 D R 15.00 
10 5 0 D Y 275.00 
11 -3 10 D Y 20.00 
12 14 -1 S N 30.00 
13 20 3 D Y -10.00 

解决方法

核心思路是:先按空白字符拆分每行的字符串字段,再将每个字段转换为对应的数据类型。以下是两种常见编程语言的实现示例:

Python 实现

Python的split()方法会自动处理多个空格的分隔,拆分后直接用类型构造函数转换即可:

# 打开数据文件
with open("data.txt", "r") as file:
    # 逐行读取处理
    for line in file:
        # 去除行首尾空白,按任意空白拆分字段
        fields = line.strip().split()
        if not fields:
            continue  # 跳过空行
        
        # 拆分并转换类型
        party_id = int(fields[0])
        meal_cost = int(fields[1])
        people_count = int(fields[2])
        # 第4个字段(如S/D/R)未在需求中提及,可根据需要保留或忽略
        is_weekend = fields[4] == "Y"
        total_bill = float(fields[5])
        
        # 验证结果(可根据需求替换为后续业务逻辑)
        print(f"派对ID: {party_id} | 餐费: {meal_cost} | 人数: {people_count} | 周末用餐: {is_weekend} | 总账单: {total_bill}")

C++ 实现

C++的cin会自动跳过空白字符,直接按变量类型读取数据,无需手动拆分:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main() {
    ifstream input_file("data.txt");
    if (!input_file.is_open()) {
        cout << "无法打开数据文件" << endl;
        return 1;
    }

    int party_id, meal_cost, people_count;
    string time_slot, weekend_flag;
    float total_bill;

    // 按类型读取每行数据
    while (input_file >> party_id >> meal_cost >> people_count >> time_slot >> weekend_flag >> total_bill) {
        bool is_weekend = (weekend_flag == "Y");
        // 验证结果
        cout << "派对ID: " << party_id 
             << " | 餐费: " << meal_cost 
             << " | 人数: " << people_count 
             << " | 周末用餐: " << boolalpha << is_weekend 
             << " | 总账单: " << total_bill << endl;
    }

    input_file.close();
    return 0;
}

注意事项

  • 数据中存在无效值(如餐费-3、人数-1、总账单-10.00),作业中可能需要添加校验逻辑,过滤或标记这些异常数据。
  • 若使用其他编程语言,核心逻辑一致:先拆分字符串字段,再做类型转换。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 13:55:20