I am trying to read a list of words from a file example.txt and sort the list an
ID: 3753933 • Letter: I
Question
I am trying to read a list of words from a file example.txt and sort the list and rewrite the sorted list to the file. So far I am able to read and sort the list but am unable to rewrite the sorted list to the file. Also the last entry is read twice how do I avoid this? C++
1 #include 2 #include 3 #include 4 #include 5 #include 7 using namespace std; 9 int main() I/create fstream instance and open file "example.txt" 2 fstream sf 3 sf.open("example.txt", fstream::out 2 fstream::in); 5 if(sf.is_open )) coutExplanation / Answer
Here is the completed code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts. Thanks
//Code
#include<iostream>
#include<algorithm>
#include<fstream>
#include<vector>
#include<string>
using namespace std;
int main(){
//opening file in read mode
ifstream inFile;
inFile.open("example.txt");
vector<string> hold;
string word;
//the correct way of extracting words from the file, without reading last
//entry twice
while(inFile>>word){
//word has been read correctly, so pushing to the vector
hold.push_back(word);
}
//closing input file
inFile.close();
//sorting the words
sort(hold.begin(),hold.end());
//opening file in write mode
ofstream outFile;
outFile.open("example.txt");
//printing sorted words into the console, also writing to the output file
for(int i=0;i<hold.size();i++){
cout<<hold[i]<<endl;
outFile<<hold[i]<<endl;
}
//closing the output file
outFile.close();
}
//example.txt before running the program
wise
harvest
survivor
railcar
meaning
agree
straighten
reliable
kick
morsel
lounge
suffering
direction
protest
short circuit
knife
opposite
arrest
big
abolish
/*OUTPUT*/
abolish
agree
arrest
big
circuit
direction
harvest
kick
knife
lounge
meaning
morsel
opposite
protest
railcar
reliable
short
straighten
suffering
survivor
wise
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.