Here's a C++ program that reads bank account data from a CSV file and displays accounts with balances over $100:

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

using namespace std;

struct BankAccount {
    string accountNumber;
    double amount;
};

int main() {
    string line;
    ifstream file('bank_accounts.csv');

    if (!file.is_open()) {
        cout << 'Error opening file!' << endl;
        return 0;
    }

    BankAccount bankAccount;
    while (getline(file, line)) {
        stringstream ss(line);
        getline(ss, bankAccount.accountNumber, ',');
        ss >> bankAccount.amount;

        if (bankAccount.amount > 100.0) {
            cout << 'Account Number: ' << bankAccount.accountNumber << ', Amount: $' << bankAccount.amount << endl;
        }
    }

    file.close();

    return 0;
}

Explanation:

  1. Include Necessary Headers:

    • iostream: For input/output operations.
    • fstream: For file handling.
    • string: For working with strings.
    • sstream: For string streams.
  2. Define a Structure:

    • BankAccount structure stores the account number (a string) and the amount (a double) for each bank account.
  3. Open the CSV File:

    • ifstream file('bank_accounts.csv');: Opens the CSV file for reading. Replace 'bank_accounts.csv' with your actual file name and path if necessary.
  4. Error Handling:

    • Checks if the file opened successfully. If not, an error message is displayed, and the program exits.
  5. Read Data from CSV:

    • while (getline(file, line)): Reads each line from the CSV file into the line string.
    • stringstream ss(line);: Creates a string stream ss from the current line.
    • getline(ss, bankAccount.accountNumber, ',');: Extracts the account number from the string stream until a comma is encountered.
    • ss >> bankAccount.amount;: Extracts the amount from the string stream.
  6. Check for Balances Over $100:

    • if (bankAccount.amount > 100.0): Checks if the amount is greater than $100.0.
    • If true, the account number and amount are printed.
  7. Close the File:

    • file.close();: Closes the CSV file after reading all the data.

Key Points:

  • Ensure your CSV file is formatted correctly with each line containing an account number followed by a comma and the amount (no spaces).
  • Replace 'bank_accounts.csv' with the actual file name and path.
  • This program assumes there are no spaces within the account numbers or amounts in the CSV file. If there are spaces, you'll need to modify the code accordingly using getline or breakstring.
  • Consider adding error handling for potential invalid data formats in the CSV file.

原文地址: https://www.cveoy.top/t/topic/o1Sk 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录