Answer to Question #183622 in C++ for shuvo

Question #183622

A teacher has asked all her students to line up according to to their first name. For example, in one class Amy will be at the front of the line and Yolanda will be at the end. Write program that reads the number of students and their names from a file. Once all the names have been read, it reports which student would be at the front of the line and which would be at the end of the line. 


1
Expert's answer
2021-04-23T13:19:32-0400
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;


//*****************************************************
//*****************File format*************************
//names may be in rows or/and columns
//all characters except for letter and digit are treated as word separators
//*****************************************************
//Mike
//Bobby
//Yolanda
//Amy
//Sonia 
//50Cent
//Liam - Olivia - Noah - Emma
//
//Oliver Ava William Sophia
//
//Elijah	Isabella	James	Charlotte
//
//Benjamin, Amelia, Lucas, Mia
//
//Mason,Harper,Ethan,Evelyn
//
//*****************************************************




bool readFromFile(const string& filePath, vector<string>& classList)
{
	ifstream fin(filePath);
	if(!fin.good())//checking if the file is open correctly
	{
		return false;
	}

	string name;
	char letter = 'c';
	while(letter != EOF)
	{
		letter = fin.get();

		if(isalnum(letter))//name can only consist of letters or numbers(why not?)
		{
			name.push_back(letter);
		}
		else//we assume any other (space, punctuation, control or EOF) character as word separator
		{
			if(!name.empty())//we do not need empty strings in class list
			{
				classList.push_back(name);
				name.clear();
			}
		}
	}
	return true;
}


int main()
{
	vector<string> classList;
	string filePath, defaultFilePath("C:\\class_list.txt");

	while(true)
	{
		cout << "Choose sourse file\n";
		cout << "(or press 'd' for default path: " << defaultFilePath << " )\n";
		cin >> filePath;
		
		if(filePath == "d")
		{
			filePath = defaultFilePath;
		}

		if( !readFromFile(filePath, classList) )
		{
			system("CLS");
			cout << "<Something went wrong while reading file '" << filePath << "'>\n";
			cout << "<Check path and try again>\n\n";
		}
		else
		{
			cout << "<File '" << filePath << "' has been read successfully>.\n\n";
			break;
		}		
	}
	
	sort(classList.begin(), classList.end());//sorting the read class list

	cout << "Total number of students: " << classList.size() << endl;
	cout << "First student in line:\n";
	cout << "-> " << classList.front() << endl;
	cout << "Last student in line:\n";
	cout << "-> " << classList.back() << endl;

	system("pause");
	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!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS