CODE In C++ Fila namesandsumames.txt contains a list of everyone in the class. C
ID: 3818824 • Letter: C
Question
Explanation / Answer
Here is the code for you:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
//Ask about the name of the input file.
string fileName;
cout << "Enter the name of the input file: ";
cin >> fileName;
//Test if file exists and asks again if not.
ifstream fin;
fin.open(fileName);
while(!fin.is_open())
{
cout << "File doesn't exist. Please enter a valid file name: ";
cin >> fileName;
fin.open(fileName);
}
//Ask about the name of the output file.
cout << "Enter the name of the output file: ";
cin >> fileName;
ofstream fout;
fout.open(fileName);
//Saving first and last name in a respective array of string
//(string Name[100] and the string surname[100]).
string Name[100], surname[100];
//Reads file line by line, and read in first and last name.
int count = 0;
while(!fin.eof())
{
fin >> Name[count] >> surname[count];
count++;
//Stop the reading and give an error message if there are
//more than 100 names (to avoid writing out of array's size)
if(count >= 100)
{
cout << "Array full. Can't read values beyond this capacity." << endl;
break;
}
}
//Print number of people.
cout << "The number of people read is: " << count << endl;
//Print the list of names with the first name first to the output file.
//(Should not be done at the same time with scanning)
for(int i = 0; i < count; i++)
fout << Name[i] << " " << surname[i] << endl;
//Filter the list by alphabetic order of first names and print the list
//of names to the output file.
for(int i = 0; i < count-1; i++)
for(int j = 0; j < count-i-1; j++)
{
if(Name[j].compare(Name[j+1]) < 0)
{
string temp = Name[j];
Name[j] = Name[j+1];
Name[j+1] = temp;
temp = surname[j];
surname[j] = surname[j+1];
surname[j+1] = temp;
}
}
for(int i = 0; i < count; i++)
fout << Name[i] << " " << surname[i] << endl;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.