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

如何在C语言中按制表符分割文本文件并赋值给变量

Parsing Tab-Separated Text File into Variables for Socket Programming

Hey there! Since you're working on socket programming and need to parse that tab-separated product data into usable variables, let's walk through how to do this clearly. I'll cover both Python and Java examples since they're common for socket work, but the core logic applies to most languages.

First, Confirm Your File Structure

First off, make sure your text file uses actual tab characters to separate fields (ID, Product Name, Quantity, Price) — this is crucial because product names have spaces (like "Coffee maker") and splitting on spaces would break the name into multiple parts. Your file should look like this (each line is one product, fields separated by tabs):

001 Coffee maker 10 3000.00
002 Pressure cooker 4 7000.00
003 Blender 10 2500.00
... (remaining entries)

Python Implementation

Python makes file parsing super straightforward. We'll read the file, split each line by tabs, and store the data in structured dictionaries (easy to use in socket communications later):

# Parse the tab-separated file into structured data
products = []

# Open the file in read mode
with open('products.txt', 'r', encoding='utf-8') as file:
    for line in file:
        # Strip newline characters and split by tab
        fields = line.strip().split('\t')
        
        # Validate we have all 4 fields before proceeding
        if len(fields) == 4:
            # Assign fields to variables, converting data types as needed
            product_id, product_name, stock_quantity, unit_price = fields
            stock_quantity = int(stock_quantity)
            unit_price = float(unit_price)
            
            # Store as a dictionary for easy access
            product = {
                'id': product_id,
                'name': product_name,
                'quantity': stock_quantity,
                'price': unit_price
            }
            products.append(product)
        else:
            print(f"Skipping malformed line: {line.strip()}")

# Example: Use the parsed variables
for item in products:
    print(f"Product ID: {item['id']} | Name: {item['name']} | Stock: {item['quantity']} | Price: ${item['price']:.2f}")

For Socket Use

If you need to send this data over a socket, convert the list of dictionaries to a JSON string (it's lightweight and easy to parse on the other end):

import json

# Convert to JSON format for socket transmission
products_json = json.dumps(products)

# Send via socket (example snippet)
# conn.send(products_json.encode('utf-8'))  # 'conn' is your socket connection

Java Implementation

If you're using Java, the logic is similar — we'll read each line, split by tabs, and encapsulate the data in a custom Product class:

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;

// Custom class to hold product data
class Product {
    String productId;
    String productName;
    int quantity;
    double price;

    public Product(String id, String name, int qty, double price) {
        this.productId = id;
        this.productName = name;
        this.quantity = qty;
        this.price = price;
    }
}

public class ProductFileParser {
    public static void main(String[] args) {
        List<Product> productList = new ArrayList<>();

        try (BufferedReader reader = new BufferedReader(new FileReader("products.txt"))) {
            String line;
            while ((line = reader.readLine()) != null) {
                String[] fields = line.split("\t");
                
                if (fields.length == 4) {
                    // Parse fields and assign to variables
                    String id = fields[0];
                    String name = fields[1];
                    int qty = Integer.parseInt(fields[2]);
                    double price = Double.parseDouble(fields[3]);
                    
                    productList.add(new Product(id, name, qty, price));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        // Example: Iterate and use the parsed data
        for (Product p : productList) {
            System.out.printf("ID: %s | Product: %s | Stock: %d | Price: $%.2f%n",
                    p.productId, p.productName, p.quantity, p.price);
        }
    }
}

Key Notes

  • Always validate the number of fields after splitting — this prevents errors from malformed lines in your file.
  • Convert string fields to appropriate data types (int for quantity, float/double for price) so you can perform calculations later if needed.
  • For socket communication, using structured formats like JSON (Python) or JSON/Java Objects (with serialization) makes data transfer and parsing much cleaner than sending raw strings.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:58:51