C++ Homework: Read the file into the 3 arrays and print them in the forward dire
ID: 3919051 • Letter: C
Question
C++ Homework:
Read the file into the 3 arrays and print them in the forward direction (in the order the data was read from the file) and then in the reverse direction.
Create a function called "PrettyPrintName" to print one row of name information (e.g. first name, last name, age). This function must be used inside a loop to print the data in the forward and reverse directions.
Here is a pic of an example executable:
Contents of NamesAndAges.txt
James Smith: 38
Michael Smith: 46
Robert Smith: 19
Maria Garcia: 32
David Smith: 21
Maria Rodriguez: 30
Mary Smith: 92
Maria Hernandez: 83
Maria Martinez: 56
James Johnson: 26?
Explanation / Answer
Program
#include <iostream> //For Input/Output
#include <fstream> //For File Input/Output
#include <string> //For Saving The Line Into The Array
#include <iomanip>
#include <cstdlib>
using namespace std;
void printArrays(string fnamearr[],string snamearr[],int agearr[],int size);
void printreverseArrays(string fnamearr[],string snamearr[],int agearr[],int size);
int main ()
{
string fname[13],sname[13]; //Array to save the name
string a,b,c;
int age[15];
int loop=0; //Index of array
ifstream myfile ("NamesAndAges.txt"); //To read from the *.txt File
if (myfile.is_open()) //Checking if the file can be opened
{
while (! myfile.eof() ) //Runs while the file is NOT at the end
{
myfile>>a>>b>>c;
fname[loop]=a; //Saves that line in the array
sname[loop]=b; //Convert to integer
age[loop]=atoi(c.c_str()); //Convert to integer
loop++; //Does an increment to the variable 'loop'
}
myfile.close(); //Closes the file
}
else cout << "Unable to open file"<<endl; //Gives an error message if the file can't be opened
printArrays(fname,sname,age,loop);
printreverseArrays(fname,sname,age,loop);
return 0;
}
void printArrays(string fnamearr[],string snamearr[],int agearr[],int size)
{
cout<<"========================"<<endl;
cout<<"Welcome to names program: "<<endl;
cout<<"========================="<<endl;
cout<<"Name Grades Age"<<endl;
cout<<"---- ------ ---"<<endl;
for(int loop2=0;loop2<size;loop2++) //For loop make to cout the lines stored
cout<<fnamearr[loop2]<<" "<<snamearr[loop2]<<" "<<agearr[loop2]<<endl; //inside of the variable 'array'
}
void printreverseArrays(string fnamearr[],string snamearr[],int agearr[],int size)
{
cout<<"========================"<<endl;
cout<<"Welcome to names program: "<<endl;
cout<<"========================="<<endl;
cout<<"Name Grades Age"<<endl;
cout<<"---- ------ ---"<<endl;
for(int loop2=size;loop2>0;loop2--) //For loop make to cout the lines stored
cout<<fnamearr[loop2]<<" "<<snamearr[loop2]<<" "<<agearr[loop2]<<endl; //inside of the variable 'array'
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.