Question

In: Computer Science

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

Solutions

Expert Solution

If you have any doubts, please give me comment...

#include <iostream>

#include <iomanip>

#include <fstream>

#include <vector>

#include <algorithm>

using namespace std;

#define MAX_SIZE 50

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

    }

};

int ageCalc(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;

    //CHANGE vector to Student array

    Student *stud_arr[MAX_SIZE] = {NULL};

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

        stud_arr[i] = &students[i];

    //CHANGE adding yougest student vector

    Student *youngest = NULL;

    int avg_age = ageCalc(stud_arr, youngest);

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

    cout << "Youngest student is " << youngest->firstName << " " << youngest->middleName << " " << youngest->lastName << endl;

    // delete[] stud_arr;

    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;

}


Related Solutions

Hello! I need to add a method that will display the total number of times the...
Hello! I need to add a method that will display the total number of times the user answered the question correctly, how many time he was right or wrong and the percentage of time they were correct in answering. import java.util.Random; import java.util.Scanner; public class Test { private static int getUserInput() { int n; Scanner scanner = new Scanner(System.in); n = scanner.nextInt(); return n; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String choice = "Yes";...
To my friendly student tax preparer: Hello, my name is Shady Slim. I understand you are...
To my friendly student tax preparer: Hello, my name is Shady Slim. I understand you are going to help me figure out my gross income for the year…whatever that means. It’s been a busy year and I’m a busy man, so let me give you the lowdown on my life and you can do your thing. I was unemployed at the beginning of the year and got $3,500 in unemployment compensation. I later got a job as a manager for...
Please Typing this My Summary from reading Chapter I need to fix My Words and make...
Please Typing this My Summary from reading Chapter I need to fix My Words and make Clear for understanding Thanks In section 4, it discusses how to adequately deal with your time. Time the board is a significant resource that you have to cause you to have as an understudy. This Part expresses half of understudies experience difficulty dealing with their time in their first year of school. School is a major distinction from secondary school, and a great deal...
Hello, I need to do a research and I choose my research question: Do the commercialization...
Hello, I need to do a research and I choose my research question: Do the commercialization and use of civilian drones respect our individual freedoms and privacy? Can you help me with ideas of Research Methodology including: 1. Restatement of research tasks: hypothesis or research questions; 2. Study population and sampling: description of study areas (where? why?), populations and the procedures for the sample selection; 3. Data collection: description of the tools (i.e. the survey instrument) and methods used (i.e....
Please Typing this My Summary from reading Chapter  I need to fix My Words and make Clear...
Please Typing this My Summary from reading Chapter  I need to fix My Words and make Clear for understanding at least 400 Words No Less than that Thanks Section 4: Time The board Section 4 discussions about how a lot of new understudies experience difficulty with time the executives, and what understudies ought to do to fix that. It begins discussing the three different ways to concentrate on time the board: investigating (seeing how you utilize your time, and what time...
/* my calculator is messed up. I need to display interest rate + initial investment. I...
/* my calculator is messed up. I need to display interest rate + initial investment. I keep getting huge numbers, Just need to fix my calculator thats all. import java.util.Scanner;//Import java scanner class public class InterestCalculator1 { //create fields / variables private double initialInvestment; private double annualInterestRate; private double numberOfYears; private double investmentReturn; private double finalAmount; Scanner input = new Scanner(System.in);//create new scanner object //constructor public InterestCalculator1(double initialInvestment, double annualInterestRate, double numberOfYears){ super(); this.initialInvestment = initialInvestment; this.annualInterestRate = annualInterestRate; this.numberOfYears...
Hello, I need some assistance on completing this program in Pseudocode and in C++ Program 2:...
Hello, I need some assistance on completing this program in Pseudocode and in C++ Program 2: Buh-RING IT! For this assignment, you’re going to simulate a text-based Role-Playing Game (RPG). Design (pseudocode) and implement (source) for a program that reads in 1) the hero’s Hit Points (HP – or health), 2) the maximum damage the hero does per attack, 3) the monster’s HP and 4) the maximum monster’s damage per attack. When the player attacks, it will pick a random...
Here is my C++ program so far. Is there anyway I can make it display an...
Here is my C++ program so far. Is there anyway I can make it display an error if the user enters a float? Thanks #include <iostream> using namespace std; // Creating a constant for the number of integers in the array const int size = 10; int main() { // Assigning literals to the varibles int a[size]; int sum=0; float avg; // For loop that will reiterate until all 10 integers are entered by the user for(int i=0; i<size; i++)...
Hello I have this error in the code, I do not know how to fix it....
Hello I have this error in the code, I do not know how to fix it. It is written in C++ using a Eclipse IDE Error: libc++abi.dylib: terminating with uncaught exception of type std::out_of_range: basic_string bus.h =========== #pragma once #include using namespace std; class Bus { private:    string BusId; // bus ID    string Manufacturer; // manufacturer of the bus    int BusCapacity; // bus capacity    int Mileage; // mileage of bus    char Status; // current status...
hello, I need a python program for a drone to follow keyboard commands - Create a...
hello, I need a python program for a drone to follow keyboard commands - Create a simple single obstacle environment and program the drone to navigate through it - Create a more advanced obstacle environment (3+ obstacles) and program the drone to navigate through it
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT