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

What\'s wrong with my code? Why it won\'t output the list of string alphabetical

ID: 3558212 • Letter: W

Question

What's wrong with my code? Why it won't output the list of string alphabetically from string.txt to output.txt?

#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
using namespace std;

int main()
{
ifstream inFile;
inFile.open("strings.txt");
string array [1000];
int i = 0;
while(inFile)
   {
string s;
getline(inFile,s);
array [i] = s;
i++;
   }
return 0;
}
void bubbleSort(string array[], int n)
{
   ofstream outFile;
outFile.open("output.txt");
  
bool swapped = true;
int j = 0;
string tmp;
while (swapped)
   {
swapped = false;
j++;
for (int i = 0; i < n - j; i++)
           {
if (array[i] > array[i + 1])
               {
tmp = array[i];
array[i] = array[i + 1];
array[i + 1] = tmp;
swapped = true;
}
}
}
}

Explanation / Answer

// FIXED CODE IS HIGH LIGHTED CODE.

#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
using namespace std;
void bubbleSort(string array[], int n); // need this header to call
int main()
{
ifstream inFile;
inFile.open("strings.txt");
string array [1000];
int i = 0;
while(inFile)
{
string s;
getline(inFile,s);
array [i] = s;
i++;
}
bubbleSort(array,i); // CALL for sorting..
inFile.close(); // close after reading from file..
return 0;
}
void bubbleSort(string array[], int n)
{
ofstream outFile;
outFile.open("output.txt");

bool swapped = true;
int j = 0;
string tmp;
while (swapped)
{
swapped = false;
j++;
for (int i = 0; i < n - j; i++)
{
if (array[i] > array[i + 1])
{
tmp = array[i];
array[i] = array[i + 1];
array[i + 1] = tmp;
swapped = true;
}
}
}
for(int i=0; i<n; i++)
outFile << array[i] << endl;
outFile.close(); // YOU HAVE TO CLOSE IT....after opening..

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote