Write to program to create a file. input user defined data entered from keyboard and write to the file. Read the contents of the file in reverse order and store to another file.
#include<iostream>
#include<string>
#include <fstream>
using namespace std;
int main()
{
int n;
string fileName="integers.txt";
cout<<"Enter number of integers: ";
cin>>n;
// write to the file.
ofstream integersFile;
integersFile.open (fileName);
for(int i=0;i<n;i++){
int num;
cout<<"Enter number "<<(i+1)<<": ";
cin>>num;
integersFile << num<<"\n";
}
integersFile.close();
int numbers[100];
int counter=0;
ifstream integersFileRead(fileName);
if(!integersFileRead){
cout << "The file '"<<fileName<<"' does not exist.\n";
}else{
int number;
while(!integersFileRead.eof()){
integersFileRead>>numbers[counter];
counter++;
}
}
integersFileRead.close();
ofstream integersReverseOrderFile;
integersReverseOrderFile.open ("integersReverseOrder.txt");
for(int i=counter-2;i>=0;i--){
integersReverseOrderFile <<numbers[i]<<"\n";
}
integersReverseOrderFile.close();
cin>>n;
return 0;
}
Comments
Leave a comment