Let’s say you have two simple text files, each file has exactly 10 lines. The fi
ID: 3770222 • Letter: L
Question
Let’s say you have two simple text files, each file has exactly 10 lines. The first file contains the names of 10 persons. Assume that a name consists of only one word (or one string) and there is one name per line. The second file contains the years in which the 10 persons were born. The years are integers. Write a C++ function that has exactly three arguments
A string variable that will accept the name of the first file.
A string variable that will accept the name of the second file.
An integer variable named “oldest” which is passed by reference.
The function should read the names of the persons and their years of birth from the first and second files, respectively. The function should do the following:
Find and display the name of the oldest person.
Find the year, the oldest person was born and stores it in the integer variable “oldest”, which was passed by reference as an argument to the function.
HINT: You might have to create arrays inside the function. You can read data from the files and store them in the arrays. The function prototype looks like this void YearFunction(string, string, int&);
Explanation / Answer
#include <stdio.h>
#include <stdlib.h>
#include <fstream>
#include <iostream>
#define MAX 1000
using namespace std;
void YearFunction(string file_first, string file_second,int& oldest)
{
ifstream infile1,infile2;
string name, cur_name, contents;
int cur_oldest;
infile1.open(file_first.c_str());
if (!infile1.is_open()) {
cerr<<"cannot open this file";
}
infile2.open(file_second.c_str());
if (!infile2.is_open()) {
cerr<<"cannot open this file";
}
int i=0;
while(i<10)
{
infile1>>cur_name;
infile2>>contents;
cur_oldest = atoi(contents.c_str());
cout<<cur_name<<" "<<contents<<endl;
if(cur_oldest<oldest)
{
oldest = cur_oldest;
name = cur_name;
}
i++;
}
cout<<name<<" is the oldest person born in "<<oldest<<endl;
return;
}
int main() {
int oldest = 1<<30;
string first = "accounts.txt",second = "transactions.txt";
printf("Enter the name of first file::");
cin>>first;
printf("Enter the name of second file::");
cin>>second;
YearFunction(first,second,oldest);
cout<<"We got the oldest one born in "<<oldest<<endl;
return 1;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.