Friday, November 3, 2023

C++ program that reads words from a file, sorts them in alphabetical order, and then writes the sorted words to another file

#include <iostream>

#include <fstream>

#include <string>


using namespace std; // Using the std namespace


// Custom sorting function to sort an array of strings

void customSort(string arr[], int size) {

    for (int i = 0; i < size - 1; i++) {

        for (int j = i + 1; j < size; j++) {

            if (arr[i] > arr[j]) {

                string temp = arr[i];

                arr[i] = arr[j];

                arr[j] = temp;

            }

        }

    }

}


int main() {

    const int MAX_WORDS = 1000; // Maximum number of words, adjust as needed

    string inputFileName = "input.txt";     // Name of the input file

    string outputFileName = "output.txt";   // Name of the output file

    string words[MAX_WORDS];               // Array to store words

    int wordCount = 0;                     // Count of words read


    // Open the input file

    ifstream inputFile(inputFileName);

    if (!inputFile) {

        cerr << "Error: Unable to open the input file." << endl;

        return 1;

    }


    // Read words from the input file

    string word;

    while (inputFile >> word && wordCount < MAX_WORDS) {

        words[wordCount] = word;

        wordCount++;

    }


    // Close the input file

    inputFile.close();


    // Sort the words in alphabetical order using the customSort function

    customSort(words, wordCount);


    // Open the output file

    ofstream outputFile(outputFileName);

    if (!outputFile) {

        cerr << "Error: Unable to open the output file." << endl;

        return 1;

    }


    // Write the sorted words to the output file

    for (int i = 0; i < wordCount; i++) {

        outputFile << words[i] << endl;

    }


    // Close the output file

    outputFile.close();


    cout << "Words have been sorted and written to " << outputFileName << "." << endl;


    return 0;

}


No comments:

Post a Comment

NaCl.xyz Generator with Interactive 3D Visualization

NaCl.xyz Generator with Interactive 3D Visualization NaCl.xyz Generator with Interactive 3D Visualization ...