Question #39738

how can I write a c++ code that counts names from a .txt file and displays the total amount of names and the first and last name alphabetically on the list?

Expert's answer

Answer on Question#39738 - Programming - C++


#include <iostream>
#include <string>
#include <string.h>
#include <fstream>
using namespace std;
#define MAX_LENGTH 50
string ToLowerCase(string str)  // helping function to make names in lower case
{
    string tempString = str;
    for(int i = 0; i < tempString.length(); ++i)
        tempString[i] = tolower(tempString[i]);
    return tempString;
}
int main()
{
    string firstName, lastName;  // objects to store first and last alphabetically names
    int count=0; // variable for counting names
    char buffer[MAX_LENGTH];  // array for reading names from file
    string tempName; // string object for storing read name
    ifstream input("names_input.txt");  // file stream for input
    if(input.bad())  // checking for opening
        return 1;
    while(!input.eof())  // while we don't reach end of file
    {
        input.getline(buffer, MAX_LENGTH);  // read line from file
        tempName = buffer;  // store name in object
        if(tempName.length() > 0)  // checking for empty line
        {
            if(count == 0)  // first name we have to write to objects
            {
                firstName = lastName = tempName;
            }
            else
            {
                if(ToLowerCase(tempName) < ToLowerCase(firstName))  // compare and write if name is good
                {
                    firstName = tempName;
                }
                if(ToLowerCase(tempName) > ToLowerCase(lastName))
                    lastName = tempName;
            }
        }
        ++count;  //increase count of names
    }
}
//output
cout << count << " names in file.\n The first alphabetically on the list is name \"" << firstName << "\". The last alphabetically on the list is name \"" << lastName << "\"\n";
return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

LATEST TUTORIALS
APPROVED BY CLIENTS