Question

Hello I need a small fix in my program. I need to display the youngest student...

Hello I need a small fix in my program. I need to display the youngest student and the average age of all of the students. It is not working Thanks.

#include <iostream>

#include <iomanip>

#include <fstream>

#include <vector>

#include <algorithm>

using namespace std;

struct Student {

string firstName;

char middleName;

string lastName;

char collegeCode;

int locCode;

int seqCode;

int age;

};

struct sort_by_age {

inline bool operator() (const Student& s1, const Student& s2)

{

return (s1.age < s2.age); // sort according to age of student

}

};

// main function to run program

int main() {

//CHANGE: vector students; TO vector students;

vector<Student> students; // create vector object to hold students data

ifstream Myfile; // create input file stream object

Myfile.open("a2data.txt"); // open file

// check if file is open

if (!Myfile.is_open()) {

// display error message if file could not be opened

cout << "Could not open the file!";

return 0; //terminate

}

//CHANGE: vector words; TO vector words;

vector<string> words; // create vector object to store words from input file

//read input from file line by line

string line;

while (!Myfile.eof()) {

getline(Myfile, line); // readline from input file stream

line.c_str(); // convert string in to char array

// file given in eample does not contain one record each line

// but it hase some patern for reading

// each word is seprated by space

//read the liine till space is encountered and get the word

int i = 0; // iterator to iterate over line

string word = "";

while (line[i] != '\0') {

// loop till end of line

if (line[i] != ' ') {

word = word + line[i]; // build word with char

i++;

}

else {

if(word!="")

words.push_back(word); // add word to vector

word = ""; //reset word to empty string

i++; //ignore white space

}

}//end of line

words.push_back(word); // add word to vector

}//end of file

//when done reading input from file close the file stream

Myfile.close();

int count = 0; // counts the words proceesed from vector object words

string fname = words.at(count); // variable to store first name of student

count++; //move to next element in the vector

//CHANGE: count < words.size() TO count < words.size() - 2

// at least two words are read in an iteration, so at least two should remain to be read - last name + student id

while (count < words.size() - 2) {

// loop till end of vector words

// create student object

Student s;

//assign first name to student

s.firstName = fname;

//next element in words is middle name

//assign first char to middle name

string mname = words.at(count);

s.middleName = mname[0];

count++;

//next element is last name of student

//assign next word to student

s.lastName = words.at(count);

//CHANGE: start

//If there was no middle name, this is the student id + first name of next student

if(words.at(count).size() >= 12) // college code + locCode + seq + age

{

if(words.at(count)[1] >= '0' && words.at(count)[1] <= '9') // if second character is a digit

{

// this is the student id field, and there is no middle name

count --; // move one step back for next iteration

s.middleName = ' '; //blank middle name

s.lastName = words.at(count);

}

}

//CHANGE: end

count++;

//next element is student id + first name of next student

//id contains college code at first latter

string id = words.at(count);

count++;

//assign college code to the student

s.collegeCode = id[0];

//next 2 char in id contain location

string loc = "";

loc = loc + id[1];

loc = loc + id[2];

// assign location to student

s.locCode = stoi(loc); // convert string to integer

//next 6 char in id contain seqcode

string seq = "";

for (int j = 3; j < 9; j++) {

seq = seq + id[j];

}

// assign seqcode to student

s.seqCode = stoi(seq); //convert string to int

//next 3 char in id contains age

string age = "";

age = age + id[9];

age = age + id[10];

age = age + id[11];

//assign age to student

s.age = stoi(age); // convert string to int

//remainig latters in id contains next student's first name

// delete id of previous student to get name of next student

fname = id.erase(0, 12); // delete first 12 char from id and assign remaining to fname

// add student to student

students.push_back(s);

}

// clear the vector as done working with words

words.clear();

//sort vector according to age of students

sort(students.begin(), students.end(), sort_by_age());

// formating output

cout << setw(15) << left << "Last Name";

cout << setw(15) << left << "Midlle Name";

cout << setw(15) << left << "First Name";

cout << setw(15) << left << "College Code";

cout << setw(12) << left << "Location";

cout << setw(12) << left << "Sequence";

cout << setw(12) << left << "Age" << endl;

cout << "=======================================================================================" << endl;

// print all students

for (int i = 0; i < students.size(); i++) {

cout << setw(15) << left << students.at(i).lastName;

cout << setw(15) << left << students.at(i).middleName;

cout << setw(20) << left << students.at(i).firstName;

cout << setw(13) << left << students.at(i).collegeCode;

cout << setw(10) << left << students.at(i).locCode;

cout << setw(12) << left << students.at(i).seqCode;

cout << students.at(i).age << endl;

}

//print average age

cout << endl;

  

int avg_age = ageCalc(arry, youngest);

cout<<"Average age is: "<<avg_age<<endl;

cout<<"Youngest student is "<<youngest->firstName<<" "<<youngest->MiddleN<<" "<<youngest->LastN<<endl;

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

delete arry[i];

}

return 0;

}

int ageCalc(Student *studs[], Student *&youngest){

youngest = studs[0];

int i = 0;

int avg_age = 0;

while(studs[i]!=NULL){

avg_age += studs[i]->age;

if(youngest->age>studs[i]->age)

youngest = studs[i];

i++;

}

return avg_age/i;

}

File needed:

https://drive.google.com/file/d/15_CxuGnFdnyIj6zhSC11oSgKEYrosHck/view?usp=sharing

0 0
Add a comment Improve this question Transcribed image text
Answer #1


//Mistakes and Modifications:
//Some syntax errors in your code like using LastN data field of Student class which is not present in it.
//you can clear the Student objects in vector by using students.clear() method of vector.
//you don't have to iterate through each vector element.
#include <iostream>
#include <iomanip>
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;
struct Student
{
string firstName;
char middleName;
string lastName;
char collegeCode;
int locCode;
int seqCode;
int age;
};
struct sort_by_age
{
inline bool operator() (const Student& s1, const Student& s2)
{
return (s1.age < s2.age); // sort according to age of student
}
};
//declare the ageCalc() method since it is implemented on bottom of the code.
//you can use vector<Student> instead of pointers of Student array.
//you can't convert the vector<Student> into *Student[] studs type.
//and you can pass the Student object youngest using reference of that object.
//reference internally considers the address no need to create Student *&youngest.
//Student &youngest will be enough.
int ageCalc(vector<Student>studs, Student &youngest);

// main function to run program
int main()
{
//CHANGE: vector students; TO vector students;
vector<Student> students; // create vector object to hold students data
ifstream Myfile; // create input file stream object
  
Myfile.open("a2data.txt"); // open file
  
// check if file is open
if (!Myfile.is_open())
{
// display error message if file could not be opened
cout << "Could not open the file!";
return 0; //terminate
}
//CHANGE: vector words; TO vector words;
vector<string> words; // create vector object to store words from input file
//read input from file line by line
string line;
while (!Myfile.eof())
{
getline(Myfile, line); // readline from input file stream
line.c_str(); // convert string in to char array
// file given in eample does not contain one record each line
// but it hase some patern for reading
// each word is seprated by space
//read the liine till space is encountered and get the word
int i = 0; // iterator to iterate over line
string word = "";
while (line[i] != '\0')
{
// loop till end of line
if (line[i] != ' ')
{
word = word + line[i]; // build word with char
i++;
}
else
{
if(word!="")
words.push_back(word); // add word to vector
word = ""; //reset word to empty string
i++; //ignore white space
}
}//end of line
words.push_back(word); // add word to vector
}//end of file
  
//when done reading input from file close the file stream
Myfile.close();
int count = 0; // counts the words proceesed from vector object words
string fname = words.at(count); // variable to store first name of student
count++; //move to next element in the vector
//CHANGE: count < words.size() TO count < words.size() - 2
// at least two words are read in an iteration, so at least two should remain to be read - last name + student id
while (count < words.size() - 2)
{
// loop till end of vector words
// create student object
Student s;
//assign first name to student
s.firstName = fname;
//next element in words is middle name
//assign first char to middle name
string mname = words.at(count);
s.middleName = mname[0];
count++;
//next element is last name of student
//assign next word to student
s.lastName = words.at(count);
//CHANGE: start
//If there was no middle name, this is the student id + first name of next student
if(words.at(count).size() >= 12) // college code + locCode + seq + age
{
if(words.at(count)[1] >= '0' && words.at(count)[1] <= '9') // if second character is a digit
{
// this is the student id field, and there is no middle name
count --; // move one step back for next iteration
s.middleName = ' '; //blank middle name
s.lastName = words.at(count);
}
}
//CHANGE: end
count++;
//next element is student id + first name of next student
//id contains college code at first latter
string id = words.at(count);
count++;
//assign college code to the student
s.collegeCode = id[0];
//next 2 char in id contain location
string loc = "";
loc = loc + id[1];
loc = loc + id[2];
// assign location to student
s.locCode = stoi(loc); // convert string to integer
//next 6 char in id contain seqcode
string seq = "";
for (int j = 3; j < 9; j++)
{
seq = seq + id[j];
}
// assign seqcode to student
s.seqCode = stoi(seq); //convert string to int
//next 3 char in id contains age
string age = "";
age = age + id[9];
age = age + id[10];
age = age + id[11];
//assign age to student
s.age = stoi(age); // convert string to int
//remainig latters in id contains next student's first name
// delete id of previous student to get name of next student
fname = id.erase(0, 12); // delete first 12 char from id and assign remaining to fname
// add student to student
students.push_back(s);
}
// clear the vector as done working with words
words.clear();
//sort vector according to age of students
sort(students.begin(), students.end(), sort_by_age());
// formating output
cout << setw(15) << left << "Last Name";
cout << setw(15) << left << "Midlle Name";
cout << setw(15) << left << "First Name";
cout << setw(15) << left << "College Code";
cout << setw(12) << left << "Location";
cout << setw(12) << left << "Sequence";
cout << setw(12) << left << "Age" << endl;
cout << "=======================================================================================" << endl;
// print all students
for (int i = 0; i < students.size(); i++)
{
cout << setw(15) << left << students.at(i).lastName;
cout << setw(15) << left << students.at(i).middleName;
cout << setw(20) << left << students.at(i).firstName;
cout << setw(13) << left << students.at(i).collegeCode;
cout << setw(10) << left << students.at(i).locCode;
cout << setw(12) << left << students.at(i).seqCode;
cout << students.at(i).age << endl;
}
  
//print average age
cout << endl;
//youngest Student object is not created in the code posted in question.
//you can pass the vector of Student objects
Student youngest;
int avg_age = ageCalc(students, youngest);
//since we have used Student object we have to print youngest object fields
//using . not -> .
cout<<"Average age is: "<<avg_age<<endl;
cout<<"Youngest student is "<<youngest.firstName<<" "<<youngest.middleName<<" "<<youngest.lastName<<endl;
int index = students.size();
//you can clear the Student objects in vector by using students.clear() method of vector.
students.clear();
return 0;
}
//method definiton.
//takes an vector of Student object and Student object reference to store the
//youngest Student.
int ageCalc(vector<Student> studs, Student &youngest)
{
//assume the first student as younges
youngest = studs[0];
int i = 0;
//average age.
int avg_age = 0;
//here vector class has method size()that returns the number of elemnets
//in vector.
int size =studs.size();
//till the index i less than size.
while(i<size)
{
//add i_th student age to avg_age.
//since we are uusing vector of Student objects
//we access object fields using . not with ->
avg_age += studs[i].age;
//since we have used Student object not pointer of Studnet object.
//we access fields using . not with ->
if(youngest.age>studs[i].age)
//modify the younges Studnet if the current youngest one age > current student.
youngest = studs[i];
//goto next student.
i++;
}
//return average.
//here you can use i or size variable both haves the
//count of total objects in passed vector.
return avg_age/i;
}
//FINAL OUTPUT --------------------

//PLEASE LIKE THE ANSWER AND COMMENT IF YOU WANT ANY MODIFICATIONS.

Add a comment
Know the answer?
Add Answer to:
Hello I need a small fix in my program. I need to display the youngest student...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Hello, I need to implement these small things in my C++ code. Thanks. 1- 10 characters...

    Hello, I need to implement these small things in my C++ code. Thanks. 1- 10 characters student first name, 10 characters middle name, 20 characters last name, 9 characters student ID, 3 characters age, in years (3 digits) 2- Open the input file. Check for successful open. If the open failed, display an error message and return with value 1. 3- Use a pointer array to manage all the created student variables.Assume that there will not be more than 99...

  • I need to make a few changes to this C++ program,first of all it should read...

    I need to make a few changes to this C++ program,first of all it should read the file from the computer without asking the user for the name of it.The name of the file is MichaelJordan.dat, second of all it should print ,3 highest frequencies are: 3 words that occure the most.everything else is good. #include <iostream> #include <map> #include <string> #include <cctype> #include <fstream> #include <iomanip> using namespace std; void addWord(map<std::string,int> &words,string s); void readFile(string infile,map<std::string,int> &words); void display(map<std::string,int>...

  • Use main.cpp, Student.h, Student.cpp (written below) and write classes StudentClub and a non-member function find youngest...

    Use main.cpp, Student.h, Student.cpp (written below) and write classes StudentClub and a non-member function find youngest to make main.cpp compile. Put the declaration and definition of find youngest in StudentClub.h and StudentClub.cpp separately. You may not modify provided files and only submit StudentClub.h and StudentClub.cpp. Non-member function find youngest is declared as follows. It returns the names of students who have the youngest age. Note there may exist more than one students who are youngest. std::vector find_youngest(const std::vector member); StudentClub...

  • I need to add something to this C++ program.Additionally I want it to remove 10 words...

    I need to add something to this C++ program.Additionally I want it to remove 10 words from the printing list (Ancient,Europe,Asia,America,North,South,West ,East,Arctica,Greenland) #include <iostream> #include <map> #include <string> #include <cctype> #include <fstream> #include <iomanip> using namespace std; void addWord(map<std::string,int> &words,string s); void readFile(string infile,map<std::string,int> &words); void display(map<std::string,int> words);    int main() { // Declaring variables std::map<std::string,int> words;       //defines an input stream for the data file ifstream dataIn;    string infile; cout<<"Please enter a File Name :"; cin>>infile; readFile(infile,words);...

  • Please help fix my code C++, I get 2 errors when running. The code should be...

    Please help fix my code C++, I get 2 errors when running. The code should be able to open this file: labdata.txt Pallet PAG PAG45982IB 737 4978 OAK Container AYF AYF23409AA 737 2209 LAS Container AAA AAA89023DL 737 5932 DFW Here is my code: #include <iostream> #include <string> #include <fstream> #include <vector> #include <cstdlib> #include <iomanip> using namespace std; const int MAXLOAD737 = 46000; const int MAXLOAD767 = 116000; class Cargo { protected: string uldtype; string abbreviation; string uldid; int...

  • I need help to fix this program it is written in c++ and needs to run...

    I need help to fix this program it is written in c++ and needs to run in visual studio. Program uses character strings from a file containing on the first line and answer key and every other line after is the students ID number followed by a space then their test answers.Program currently reads only test answer key and student ID and their answers of second line.  Sample data can be found below. TFTTFTFFFTTTFFTTFFFT HUB00123 TFTFFFTFTFTFTTTFTTTT SMU12456 FFTFTTFFTTTTTTFFTTFT #include #include #include...

  • The following C++ code include 3 files: Patient.h, Patient.cpp and Main.cpp. The program basically creates and stores patient records. The original code has everything in a single .cpp file. I tried t...

    The following C++ code include 3 files: Patient.h, Patient.cpp and Main.cpp. The program basically creates and stores patient records. The original code has everything in a single .cpp file. I tried to divide the code in 3 parts (Patient.h, Patient.cpp and Main.cpp), but it is giving me errors. Patient.h #ifndef PATIENT_H #define PATIENT_H #include <string> #include "Patient.cpp" using namespace std; class Patient{ private : string firstname; string lastname; string location; static int cnt; int id; public : Patient(string, string, string);...

  • Expand the payroll program to combine two sorting techniques (Selection and Exchange sorts) for better efficiency...

    Expand the payroll program to combine two sorting techniques (Selection and Exchange sorts) for better efficiency in sorting the employee’s net pay. //I need to use an EXSEL sort in order to combine the selection and Exchange sorts for my program. I currently have a selection sort in there. Please help me with replacing this with the EXSEL sort. //My input files: //My current code with the sel sort. Please help me replace this with an EXSEL sort. #include <fstream>...

  • I want to change this code and need help. I want the code to not use...

    I want to change this code and need help. I want the code to not use parallel arrays, but instead use one array of struct containing the data elements, String for first name, String for last name,Array of integers for five (5) test scores, Character for grade. If you have any idea help would be great. #include #include #include #include using namespace std; const int NUMBER_OF_ROWS = 10; //number of students const int NUMBER_OF_COLUMNS = 5; //number of scores void...

  • Hi I need a fix in my program. The program needs to finish after serving the...

    Hi I need a fix in my program. The program needs to finish after serving the customers from the queue list. Requeriments: Headers: DynamicArray.h #ifndef DynamicArray_h #define DynamicArray_h #include using namespace std; template class DynamicArray { V* values; int cap; V dummy; public: DynamicArray(int = 2); DynamicArray(const DynamicArray&); ~DynamicArray() { delete[] values; } int capacity() const { return cap; } void capacity(int); V operator[](int) const; V& operator[](int); DynamicArray& operator=(const DynamicArray&); }; template DynamicArray::DynamicArray(int cap) { this->cap = cap; values =...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT