C++ Program to Read Bank Accounts from CSV and Display Balances over $100
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:
-
Include Necessary Headers:
iostream: For input/output operations.fstream: For file handling.string: For working with strings.sstream: For string streams.
-
Define a Structure:
BankAccountstructure stores the account number (a string) and the amount (a double) for each bank account.
-
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.
-
Error Handling:
- Checks if the file opened successfully. If not, an error message is displayed, and the program exits.
-
Read Data from CSV:
while (getline(file, line)): Reads each line from the CSV file into thelinestring.stringstream ss(line);: Creates a string streamssfrom 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.
-
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.
-
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
getlineorbreakstring. - Consider adding error handling for potential invalid data formats in the CSV file.
原文地址: https://www.cveoy.top/t/topic/o1Sk 著作权归作者所有。请勿转载和采集!