Write a C++ program that will read names followed by single test grade. The very
ID: 664154 • Letter: W
Question
Write a C++ program that will read names followed by single test grade. The very first line of the file has a single number which represents the max number of points to make on a test. The name is listed first followed by a grade or the points made on a test. Have your program read in the name and grade and print out the name and the percentage grade the student made on the test. (grade/max=%). Print out the list of names and their grade in sorted order sorted by grade. You are to list the sorted grades from the highest grade to the lowest.
You are to use a link list for the data structure.
Example input
300
jones 289
luewey 266
Or-less 178
Example output (Sorted): (Example is not accurate)
Jones 94
Luewey 90
Or-less 83
Input File:
Explanation / Answer
#include <iostream>
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
struct node {
int grade;
string name;
node *next;
};
void sorting(node *head)
{
node *temp = head;
node *tempnode = 0;
node *switchNode = 0;
temp = head;
while (temp != 0)
{
tempnode = temp->next;
while (tempnode != 0)
{
if (tempnode->grade > temp->grade)
{
//just switch data
int temp1 = temp->grade;
temp->grade = tempnode->grade;
tempnode->grade = temp1;
string s = temp->name;
temp->name = tempnode->name;
tempnode->name = s;
}
tempnode = tempnode->next;
}
temp = temp->next;
}
}
void printLinkedList(node *head)
{
node *temp = head;
while (temp != 0)
{
cout << temp->name << " " << temp->grade << endl;
temp = temp->next;
}
}
int main()
{
node *root,*temp; // This will be the unchanging first node
temp = root = 0;
ifstream myfile("data.txt");
string line;
int maxNum;
if (myfile.is_open())
{
getline(myfile, line);
maxNum = stoi(line);
while (getline(myfile, line))
{
node *data = new node;
data->next = 0;
data->name = line.substr(0, line.find(" "));
data->grade = stoi(line.substr(line.find(" ")))*100/maxNum;
if (temp == 0)
{
root = data;
temp = root;
}
else
{
temp->next = data;
temp = temp->next;
}
}
myfile.close();
sorting(root);
printLinkedList(root);
}
root = new node; // Now root points to a node struct
root->next = 0; // The node root points to has its next pointer
// set equal to a null pointer
// a pointer (root in this case) points to.
system("pause");
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.