In: Computer Science
For this assignment you will write a C++ program to read a list of words and sort them in alphabetical order.
Requirements:
NOTES:
word_list.txt
_____________________________________________________________________________________________________________________________________below:
# Read the list of words below and write them out in alphabetical order. # Your program should skip over the blank lines. goal interesting successful job experience career manage responsibility technology purpose beautiful wonder opportunity leader quality knowledge victory nature ability dream understand future hope
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
// this function sorts given vector using bubble sort
void bubble_sort(vector<string> &words)
{
for (int i = 0; i < words.size() - 1; i++)
{
for (int j = 0; j < words.size() - i - 1; j++)
{
if (words[j] > words[j + 1])
{
// below 3 lines swaps j and j+1 word in vector
string temp = words[j];
words[j] = words[j + 1];
words[j + 1] = temp;
}
}
}
}
int main()
{
ifstream input("word_list.txt");
// file not found
if (!input.is_open())
{
cout << "Can't open file\n";
return 0;
}
// vector of words
vector<string> words;
string line;
// read line till end
while (getline(input, line))
{
// blank and lines starting with #
if (line.size() == 0 || line[0] == '#')
continue;
words.push_back(line);
}
// sort using bubble sort
bubble_sort(words);
// print vector
cout << "Sorted words:\n\n";
for (int i = 0; i < words.size(); i++)
{
cout << words[i] << endl;
}
input.close();
}
Output:
