Q2) Write a C++ program that reads a list of words from a text file into a vecto
ID: 3711645 • Letter: Q
Question
Q2) Write a C++ program that reads a list of words from a text file into a vector of strings, sorts the words in descending alphabetical order, and then writes the sorted list to another text file. Assume that both the input and output files are formatted with only one word on each line. An example file input/file output pair is provided below: Input file: Output file: Jim Ted Paula Helen Rachel Ted Raachel Paula Jim Helen Hint: You may use bubble sort (from lecture) or selection sort (from homework 3). However, you must rewrite the sorting algorithm to work on a vector of strings. Note: You must write your code in a source file named sort list.cpp. In your code, you must read from a text file named list_in.txt and write to a text file named list out.txt. You are provided an example input text file to test your code. Use the string and vector types that are accessible when you include and , respectively. Use file input and output streams to read from and write to the files (make sure to include )Explanation / Answer
C++ CODE:
Here in this code the words from the text file into a vector of strings , and are sorted in decending order and is written in another text file.
#include<iostream>
#include<fstream>
#include<vector>
using namespace std;
void bubbleSort(vector<string> &v) {
int n = v.size();
string temp = "";
for(int i=0; i < n; i++){
for(int j=1; j < (n-i); j++){
if(v[j-1] > v[j]){
temp = v[j-1];
v[j-1] = v[j];
v[j] = temp;
}
}
}
}
int main() {
vector<string> v;
ifstream inputFile;
inputFile.open("list_in.txt");
string word;
if (inputFile.is_open()) {
while (!inputFile.eof()) {
inputFile >> word;
v.push_back ;
}
}
bubbleSort(v);
ofstream outputFile;
outputFile.open ("list_out.txt");
for(int i=0; i<v.size(); i++){
outputFile <<v[i]<<endl;
}
cout<<"The file generated is"<<endl;
outputFile.close();
inputFile.close();
return 0;
}
OUTPUT:
h-4.2$ g++ -std=c++11 -o main *.cpp
sh-4.2$ main
The file generated is
list_out.txt
Ann
Jalil
James
Jane
Matt
Nick
Shawn
Shuanshuan
Vincent
Viola
Wei
Will
William
Zahra
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.