Your friend Raphael is again facing another predicament. His elementary school wanted him to submit his class roster as a .txt file, which would contain the enrollment numbers and the names of each of the students. Initially, he had put down the data in the format of <enrollment no.> <first_name> <last_name&rt;. However, the school, being in Japan, writes names in reverse order, ie they write the names in the format <last name> <first name>.
Raphael does not have the time to rewrite the rosters for all his students. He wants your help to change the formatting to what the school wants: <enrollment no.> <last_name> <first_name>.
Write a program in C++ that reads in a file named records.txt, which contains the records of the students in the first format, and fixes the records in the second format and churns out a file named records_fixed.txt.
63628 Kaho Suzuki
63271 Akito Nakayama
83729 Hikari Ayachi
63628 Suzuki Kaho
63271 Nakayama Akito
83729 Ayachi Hikari
This is a simple exercise in file I/O. Note that each line of records.txt consists of an int roll
, a string firstname
, and a string lastname
. You should just read in these things in order and write to records_fixed.txt in the fixed order.
#include <iostream> #include <fstream> using namespace std; int main() { int roll; string firstname, lastname; ifstream fin("records.txt",ios::in); ofstream fout("records_fixed.txt",ios::out); if(!fin.is_open() || !fout.is_open()) // If there was some error opening these files, abort. { cout<<"Error opening records.txt or records_fixed.txt..."; return 1; } // Read in the records via fin and write them out via fout! while(!fin.eof()) { fin>>roll>>firstname>>lastname; fout<<roll<<" "<<lastname<<" "<<firstname<<endl; } // Close the file streams after finishing your work. fin.close(); fout.close(); cout<<"Fixing records complete.\n"; return 0; }