In: Computer Science
Write a C++ program in a file called pop.cpp that opens a file called pop.dat which has the following data (you’ll have to create pop.dat)
AX013 1.0
BX123456 1234.56
ABNB9876152345 99999.99
The data are account numbers and balances. Account numbers are, at most 14 characters. Balances are, at most, 8 characters (no more than 99999.99). Using a loop until the end of file, read an account number and balance then write these to standard output in the following format shown below. Use the I/O manipulators setw, left, and right. Set the precision/fixed/showpoint so that all numeric data is written are written with exactly two digits to the right of the decimal.
Account Number Balance
-------------------------
AX013 $ 1.00
BX123456 $ 1234.56
ABNB9876152345 $ 99999.99
CODE:
#include<iostream>
#include<iomanip>
#include<bits/stdc++.h>
#include<sstream>
using namespace std;
void readFile(string filename){
//reading and opening the file
fstream file;
file.open(filename.c_str());
string word;
//printing the header
cout<<setw(20)<<left<<"Account
Number"<<setw(15)<<left<<"Balance"<<endl;
cout<<setw(20)<<left<<"--------------"<<setw(15)<<left<<"-------"<<endl;
int counter = 0;
//reading the file
while(file>>word){
//if counter == 0
if(counter == 0){
//it is a bank account number
cout<<setw(20)<<left<<word<<"$ ";
counter = 1;
}else if(counter == 1){
//if counter is 1 it is the balance
stringstream ss(word);
//converting string to double
cout.precision(2);
double x;
ss>>x;
//printing the balance
cout<<setw(15)<<left<<fixed<<x<<endl;
counter = 0;
}
}
//closing the file
file.close();
}
//main method
int main(){
//calling the file
readFile("pop.dat");
return 0;
}
__________________________________________
CODE IMAGES:
______________________________________________
OUTPUT:
pop.dat
__________________________________________
Feel free to ask any questions in the comments section
Thank You!