In: Computer Science
Using C++ Use dynamic allocation and functions (using pointer variables only) to read the names from the .txt file and sort the names in lexical order
Grumpy
Dopey
Doc
Happy
Bashful
Sneezy
Sleepy
Note: Could you plz go through this code and let me
know if u need any changes in this.Thank You
=================================
#include <fstream>
#include <iostream>
#include <cstring>
using namespace std;
void sort(string names[], int count);
int main()
{
// Declaring variables
string* names = NULL;
int count = 0;
string name;
ifstream dataIn;
// open the input file
dataIn.open("strnames.txt");
/*
* checking whether the file name is valid or not
*/
if (dataIn.fail())
{
cout << "** File Not Found **";
return 1;
}
else
{
/*
* Reading the data from the file
*/
while (dataIn >> name)
{
count++;
}
/*
* closing the file
*/
dataIn.close();
// Creating array dynamically
names = new string[count];
dataIn.open("strnames.txt");
for (int i = 0; i < count; i++)
{
dataIn >> names[i];
}
dataIn.close();
cout << "Before Sorting :" << endl;
for (int i = 0; i < count; i++)
{
cout << names[i] << endl;
}
sort(names, count);
cout << "After Sorting :" << endl;
for (int i = 0; i < count; i++)
{
cout << names[i] << endl;
}
}
return 0;
}
// this function will sort the string in lexical order
void sort(string names[], int size_of_arr)
{
string temp;
for (int i = 0; i < size_of_arr - 1; i++)
{
for (int j = 0; j < size_of_arr - i - 1; j++)
{
if (names[j] > names[j + 1])
{
temp = names[j];
names[j] = names[j + 1];
names[j + 1] = temp;
}
}
}
}
==========================================
==============================================
Output:
=====================Could you plz rate me well.Thank You