Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

what inside of list_in.txt is: James Ann Jane Viola William Shawn Vincent Will N

ID: 3820865 • Letter: W

Question

what inside of list_in.txt is:

James
Ann
Jane
Viola
William
Shawn
Vincent
Will
Nick
Jalil
Shuanshuan
Zahra
Matt
Wei

Q2) Write a C++ program that reads a list of words from a text file into a vector of strings, sorts the words in 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 Helena Ted Jim Paula Paula Helen Rachel Rachel Ted 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

Explanation / Answer

#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(word);
}
}
bubbleSort(v);
ofstream outputFile;
outputFile.open ("list_out.txt");
for(int i=0; i<v.size(); i++){
outputFile <<v[i]<<endl;
}
cout<<"File has been generated"<<endl;
outputFile.close();
inputFile.close();
return 0;
}

Output:

h-4.2$ g++ -std=c++11 -o main *.cpp                                                                                                                                                                                                                                     

sh-4.2$ main                                                                                                                                                                                                                                                             

File has been generated

list_out.txt

Ann
Jalil
James
Jane
Matt
Nick
Shawn
Shuanshuan
Vincent
Viola
Wei
Will
William
Zahra