You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

C++技术实现:从文件读取数据并格式化展示为整洁表格

Alright, let's build this C++ program together. I'll walk you through the whole thing, including handling that tricky farm name with spaces and making the output look clean and organized.

Solution for Reading Farm Data & Formatting Console Output

Step 1: Complete the Required Headers

You already started with some, but we need a few more for file handling and string manipulation:

#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <limits> // For input cleanup

Step 2: Full Working Code (With Comments)

Here's the complete program tailored to your needs. I've added notes to explain key parts:

int main() {
    // Replace "farm_data.txt" with your actual file path (use absolute path if needed)
    std::ifstream inputFile("farm_data.txt");
    
    // Check if the file opened successfully
    if (!inputFile.is_open()) {
        std::cerr << "Oops! Couldn't open the input file. Check the path and try again." << std::endl;
        return 1;
    }

    // Set up formatting rules for consistent, neat output
    std::cout << std::left; // Align text to the left for better readability
    std::cout << std::fixed << std::setprecision(2); // Force 2 decimal places for currency

    // Optional header to make the table clearer
    std::cout << std::setw(22) << "Farm Name" 
              << std::setw(15) << "Item Count" 
              << "Total Value" << std::endl;
    std::cout << "--------------------------------------------------------" << std::endl;

    // Variables to store each line's data
    std::string farmName;
    int itemQuantity;
    std::string itemName;
    double unitPrice, totalPrice;

    // Read each line of the file
    while (std::getline(inputFile, farmName, ',')) {
        // Skip the space immediately after the comma
        inputFile.ignore();

        // Read the rest of the line's data
        inputFile >> itemQuantity >> itemName >> unitPrice >> totalPrice;
        // Clear any leftover characters/newlines to avoid messing up the next iteration
        inputFile.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

        // Print formatted output exactly as you requested
        std::cout << std::setw(22) << farmName 
                  << std::setw(15) << itemQuantity << " items contributed" 
                  << " totaling $" << totalPrice << std::endl;
    }

    // Clean up: close the file
    inputFile.close();
    return 0;
}

Step 3: Key Details Breakdown

  • Handling Spaced Farm Names: Since names like "Bart Smith Farms" have spaces, we use std::getline(inputFile, farmName, ',') to read everything up to the comma — this preserves spaces in the farm name instead of stopping at the first space.
  • Consistent Formatting: std::setw(n) sets a fixed width for each field, so columns line up perfectly. std::fixed and std::setprecision(2) ensures total prices always show two decimal places (even if they're .00).
  • Error Prevention: We check if the file opens successfully, and clear leftover input characters to avoid bugs when reading subsequent lines.

Step 4: Example Output

Using your sample data, the console will show:

Farm Name               Item Count       Total Value
--------------------------------------------------------
Collins Farm            43900 items contributed totaling $29413.00
Bart Smith Farms        34910 items contributed totaling $34560.90
Allen Farms             117 items contributed totaling $63.18

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

火山引擎 最新活动