DISCLAIMER: I know it's not practical to use two vectors, but that's our assignment.
Here's my prompt:
In this program, we are going to input the name and score of 100 students from a file named
student.txt. This file has been provided to you. You have to use two vector variables, one to store the
student names, and another to store the student scores. Further, modify the selectionSort function to
sort the student information based on the score in ascending order. Finally, display the sorted student
information on the screen by using cout.
For example, let us assume, the following is the content of the student.txt file (in this case, we have
only 4 value pairs).
Jeff 77
Charles 99
Richard 67
Sina 79
Then, the output of the program would be
Charles 99
Sina 79
Jeff 77
Richard 67
Here's my code:
//Name
//This program will read and sort names and grades from a file using functions and vectors
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
#include <vector>
using namespace std;
//Function prototype
void selectionSort(vector<int>& vector_values);
int main()
{
ifstream infile;
infile.open("student.txt");
if (infile.fail() == false)
{
vector<string> all_names;
vector<int> all_scores;
string name;
int score;
while (infile >> name >> score) // read one name and one score
{
all_names.push_back(name); // add that name to vector
all_scores.push_back(score); // add that score to vector
int count = 0;
const int max = 1;
selectionSort(all_scores);
while (count < max)
{
count++;
cout << name << " " << score << endl;
}
}
}
else
{
cout << "Could not open the file." << endl;
}
return 0;
}
void selectionSort(vector<int>& vector_values)
{
for (unsigned pass = 0; pass < vector_values.size(); pass++)
{
int minimum = vector_values[pass];
int minimum_index = pass;
for (unsigned index = pass + 1; index < vector_values.size(); index++)
{
if (minimum > vector_values[index])
{
minimum = vector_values[index];
minimum_index = index;
}
}
int temp = vector_values[minimum_index];
vector_values[minimum_index] = vector_values[pass];
vector_values[pass] = temp;
}
}
Here's my problem:
The code compiles just fine and shows the names and their corresponding score, however, it seems that my sorting function is doing absolutely nothing. The names are displaying in the same order they do in the file originally. I have placed the call in every location that I thought it would go, and nothing changed. I am now concerned that the placement of the call isn't the issue, but the entire function.
This statement
cout << name << " " << score << endl;
just prints the two values that you just read. It doesn't matter whether you sorted anything in between.
But you're not sorting the all_names array either. And sorting after adding each item is highly inefficient.
I've set my array size to 20 (I set it to 19 assuming it's counting 0). I set my for loop to only run so long as gradeCount <= to gradeCounted yet it will keep running no matter how many times I enter data. If I enter 3 grades without pressing enter between each one, such as "23 23 23" it will return "Enter Grade" 3 times in a row, rather, for as many grades as I enter, separated by spaces. I don't understand why it's not passing data into the array and ending the for loop properly. I'm sure my code is an ugly mess, sorry.
Also, when entering code into stackoverflow, it said to indent the code 4 spaces to format? I couldn't initially indent the code with the code button and there was no {} button either. What am I missing? It was only after a notification to fix it that I was able to. Thanks for your time, I don't want to be a pain in the ass for you guys.
//This program asks user how many grades there are, inputs grades, and displays median of said grades.
#include <iostream>
using namespace std;
//Variables
////////////////////const int limitGrades = 20; //Array "boxes"? //Ignore this //for now.
int gradeCounted; //Number of grades from user.
const int SIZE = 19;
//Array
float grades[19]; //Max grades that can be entered.
//Functions
void gradeTaker()
{
cout << "You may input up to 20 grades. \n";
cout << "First enter the number of grades you have: \n";
cin >> gradeCounted;
//requests how many grades there are and stores them in array
for (int gradeCount = 0; gradeCount <= gradeCounted + 1; gradeCount++)
{
for (float &grade : grades)
{
cout << "Enter grade: \n";
cin >> grade;
}
}
};
int main()
{
gradeTaker();
cout << "grades so far";
for (int grade : grades)
cout << grade << endl;
system("pause");
}
The size of the array is separate from how you access it. Accessing 20 values is the equivalent to accessing indices from 0 to 19.
float grades[20];
for(size_t i = 0; i < 20; i++){ // print all values of grades
std::cout << grades[i] << "\n";
}
Furthermore, your for loop in gradeTaker will ask you for a value for each index of grades a total of gradeCounted + 2 times. To fix this, only iterate over the indices that you're assigning a value to like so:
for (int gradeCount = 0; gradeCount < gradeCounted; gradeCount++){
cout << "Enter grade: \n";
cin >> grade[gradeCount];
}
Finally... the for loop in your main function will iterate across the entire array which may include uninitialized values. You should initialize the array or use a dynamic data structure like std::vector and just push_back the necessary values.
(P.s. highlight code in the text-block and press CTRL+K to indent.)
My first question here, though I've lurked for a while. Very new to programming, sorry for bad formatting in this post, my brain is fried. I like to do the homework completely on my own, but I'm completely snagged at this point.
We are to retrieve and process data in a scenario where five different types of salsa are being sold. I know how to display the string of salsa types, I know how to process it once the user enters the correct number of jars sold.
I'm stuck on trying to get the user input number of jars sold to appear after each salsa type is listed.
ex: Enter the number of jars sold according to salsa type
Mild: (User enters data here)
Medium: (User enters data here)
etc.
I can only seem to get user input data to appear after the names are listed:
Enter the number of jars sold according to salsa type
Mild:
Medium:
etc.
(User enters data here)
Heres what I have so far:
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
int main()
{
// variables
const int SIZE = 5;
string salsas[SIZE] = { "Mild", "Medium", "Sweet", "Hot", "Zesty"};
//names of salsas
int jars; //holds number of jars user enters
cout << "Here are the salsa types:\n";
// Display the salsas in the array
for (int count = 0; count < SIZE; count++)
cout << salsas[count] << ": " << endl;
cin >> jars[salsas];
return 0;
}
Any help is appreciated!
#include <iostream>
#include <string>
using namespace std;
int main(){
// variables
const int SIZE = 5;
string salsas[SIZE] = { "Mild", "Medium", "Sweet", "Hot", "Zesty"};
//names of salsas
int jars[SIZE]={0}; //holds number of jars user enters
cout << "Here are the salsa types:\n";
// Display the salsas in the array
for (int count = 0; count < SIZE; count++) {
cout << salsas[count] << " : ";
cin >> jars[count];
}
return 0;
}
I am working on an assignment for my C++ class (the assignment is pasted at the bottom of my test.cpp file). I implemented everything correctly up until the last requirement (using a sort_name function, sort the student structures based on their last names and for each student, sort the classes he or she is taking based on class title. Display the sorted list of students using the display function by calling it from main). I have attempted to implement my sort function by sorting just the students at first, but I keep getting errors and getting stuck(The current error is: Unhandled exception at 0x777a15de in 839a4 Vasilkovskiy.exe: 0xC00000FD: Stack overflow). Any help would be greatly appreciated.
NOTE: I understand that vectors are much more useful for sorting, but our professor does not want us to use them.
#include <iostream>
#include <string>
#include <stdio.h>
#include <string.h>
#include <iomanip>
using namespace std;
struct Class
{
string title;
int units;
char grade;
};
struct Student
{
string name;
double gpa;
Class classes[500];
};
int const SIZE = 50;
void initStudent(Student[], int);
void readStudent(Student[], int, int&);
void gpaCalculate(Student&);
void print(Student[], int);
void sort_name(Student[], int);
void swapStus(Student&, Student&);
void stringToCharArray(string, char[]);
int locactionOfFirstName(Student[], int, int);
int main()
{
int numberOfStudents = 0;
Student students[SIZE];
initStudent(students, SIZE);
readStudent(students, SIZE, numberOfStudents);
for(int i = 0; students[i].name != "";i++)
gpaCalculate(students[i]);
print(students, numberOfStudents);
sort_name(students, numberOfStudents);
system("pause");
return 0;
}
void initStudent(Student st[], int s)
{
for(int i = 0; i < s; i++)
{
st[i].gpa = 0.0;
}
}
void readStudent(Student st[], int s, int& nStus)
{
for(int i = 0; i < s; i++)
{
string tmpName;
cout << "Enter student name: ";
getline(cin, tmpName);
if(tmpName == "")
break;
st[i].name = tmpName;
nStus++;
for(int j = 0; j < 500; j++)
{
string tmpTitle;
cout << "Enter class title: ";
getline(cin, tmpTitle);
if (tmpTitle == "")
break;
st[i].classes[j].title = tmpTitle;
cout << "Enter units for " << st[i].classes[j].title << ": " ;
cin >> st[i].classes[j].units;
cout << "Enter grade for " << st[i].classes[j].title << ": " ;
cin >> st[i].classes[j].grade;
cin.ignore();
}
}
}
void gpaCalculate (Student& s)
{
double unitsByPoints = 0;
double totalUnits = 0;
for (int i = 0; s.classes[i].title != ""; i++)
{
int grade = 0;
char ltrGrade = s.classes[i].grade;
switch (ltrGrade)
{
case 'A':
grade = 4;
break;
case 'B':
grade = 3;
break;
case 'C':
grade = 2;
break;
case 'D':
grade = 1;
break;
case 'F':
grade = 0;
break;
}
unitsByPoints += s.classes[i].units*grade;
totalUnits += s.classes[i].units;
}
s.gpa = unitsByPoints/totalUnits;
}
void print(Student st[], int size)
{
for (int i = 0; i < size; i++)
{
cout << "Student's name: " << st[i].name << endl;
for (int j = 0; st[i].classes[j].title != ""; j++)
{
cout << st[i].classes[j].title << "," << st[i].classes[j].grade << endl;
}
cout << fixed << setprecision(2) << "GPA: " << st[i].gpa << endl;
}
}
//void sort_name(Student st[], int size)
//{
// for(int i = 0; i < size; i++)
// {
// int smallest = locactionOfFirstName(st, i, size);
// swapStus(st[i], st[smallest]);
// }
//
//}
void swapStus(Student& s1, Student& s2)
{
Student tempStu;
tempStu = s1;
s1 = s2;
s2 = tempStu;
}
void stringToCharArray(string s, char c[])
{
char tempCharArray[50];
for(int i = 0; s[i] != '\n'; i++)
{
tempCharArray[i] = s[i];
}
char * space = strstr(tempCharArray," ");
strcpy(c,space);
}
bool lastNameCompare(string l1, string l2)
{
char lName1[50];
char lName2[50];
stringToCharArray(l1, lName1);
stringToCharArray(l2, lName2);
return (strcmp(lName1, lName2) >=0);
}
int locactionOfFirstName(Student st[],int start, int size)
{
char lName1[50];
char lName2[50];
stringToCharArray(st[0].name, lName1);
int i;
for(i = start; i < size;)
{
stringToCharArray(st[i].name, lName2);
if(strcmp(lName1, lName2) >= 0 )
{
stringToCharArray(st[i].name, lName1);
}
}
return i;
}
void InsertItem(Student values[], int startIndex, int endIndex)
{
bool finished = false;
int current = endIndex;
bool moreToSearch = (current != startIndex);
while (moreToSearch && !finished)
{
if (lastNameCompare(values[current-1].name, values[current].name))
{
swapStus(values[current], values[current-1]);
current--;
moreToSearch = (current != startIndex);
}
else
finished = true;
}
}
void sort_name(Student values[], int numValues)
{
for (int count = 0; count < numValues; count++)
InsertItem(values, 0, count);
}
/*
Define a structure called Class (with uppercase C) with the following data:
title, units and grade.
Define a structure called Student with the following data:
name (full name), gpa, and classes which is an array of Class structures (all the classes the student has taken so far).
Write an initialize function that receives an array of Student structures and its size and sets the gpa of all to 0.0.
In main, create 50 Students and call the above function to initialize the gpa for all 50 Students to 0.0.
Then, pass the array of student structures and its size to a read function that will read student data from the user and store the entered data in the array of student structures. The user will enter student name followed by the class title, units and grade received for each class he or she has taken. When finished entering class information for a student, the user will just press Enter (an empty string) and to end entering more students, he or she will do the same for the student name.
Example:
Enter student name: Maria Gomez
Enter class title: English 101
Enter units for English 101: 3
Enter grade for English 101: A
Enter class title: Math 201
Enter units for Math 201: 4
Enter grade for Math 201: B
Enter class title: [User enters RETURN to indicate no more classes]
Enter student name: Kevin Duran
Enter class title: Poly Sci 101
Enter units for Poly Sci 101: 3
Enter grade for Poly Sci 101: A
Enter class title: Math 201
Enter units for Math 201: 4
Enter grade for Math 201: B
Enter class title: [User enters RETURN to indicate no more classes]
Enter student name: [User enters RETURN to indicate no more students]
Once all Studnets have been entered, pass each element of the array of Student structures (element by element) to a gpa function which will compute and return the gpa for each Student using the classes array within each Student structure which contains the units and grade for each class taken by the student. Store the gpa returned by the above function in the gpa member of the Student structures. GPA is calculated by multiplying the number of units for each class by the points received for that class, and then adding all these products together and dividing it by total number of units. The points received for a class is based on the grade: for A, it's 4; for B, it's 3; for C, it's 2; for D it's 1; and for F it's 0. For example, if a student has take 3 classes with 3, 4, and 3 units and has received A, B, and C for these classes, respectively, then, the GPA will be 3 x 4 + 4 x 3 + 3 x 2 / 10 = 3.0.
Print all students showing name, followed by all classes taken, the grade received and the gpa using a display function which receives the array and its size as parameters.
Then, using a sort_name function, sort the student structures based on their last names and for each student, sort the classes he or she is taking based on class title. Display the sorted list of students using the display function by calling it from main.
For example:
Kevn Duran
Poly Sci 101, A
Math 150, B
GPA: 3.0
Maria Gomez:
English 101, A
Math 201, C
GPA: 2.9
Robert Small
Comp Science 801, C
Comp Science 802, D
GPA: 1.9
Tom Wang
Comp Science 808, A
Comp Science 839, B
GPA: 3.5
Then, sort the students based on their GPA's using a sort_gpa function and print the list again using the display function.
Then, ask what to search for - name or gpa. If name is selected, read a student name from the user and, using a binary search function that takes the array, its size and the name to search for, finds the student and displays all of his or her information (name, gpa, units and list of classes taken).
Example:
Enter a student name: Robert Small
Robert Small:
Comp Science 801, C
Comp Science 802, B
GPA: 2.5
If GPA is selected, read a GPA and using another binary search find the student with the given GPA by passing the students array, its size and the GPA to search for. Display the name of the student with the specified GPA in main.
Example:
Enter GPA to search for: 2.5
Robert Small was found with the GPA of 2.5
If the name or GPA is not found, tell the user it was not found; e.g.: There was no student with a GPA of 2.5; or Robert Small was not found.
Then, pass the array of student atructures and the size to a stats function which will return the average of the GPA's of all students and through two reference parameters will output the student structures that have the minimum and maximum GPA's. Print the average GPA, as well as the names of the students who have the minimum and maximum GPA in main, like so:
Average GPA = 3.17
Robert Small has the minimum GPA of 2.5.
Tom Wang has the maximum GPA of 3.5.
Finally, read a maximum and minimum GPA from the user and pass the array of student structures and its size, as well as two other arrays of student structures of the same size to a function which will store all students with a GPA of above the minimum in the highGPA array and all those with a GPA below the maximum in the lowGPA array. Display the students stored in these two arrays by passing them each from main to the display function. In other words, the highlow function receives two uninitalized arrays of student structures and populates them based on the GPA criteria passed to it (minimum GPA and maximum GPA). Then, upon return to main, main passes each of these arrays to the display function to display them. For example, if the user enters 2.0 for the maximum GPA, the lowGPA array gets filled out with all those students who have a GPA of less than 2.0. Likewise, if the minimum GPA is 3.5, the highlow function populates the highGPA array with those students who have a GPA of 3.5 or higher.
Example:
Enter maximum GPA: 2.0
Enter minimum GPA: 3.5
Students with a GPA of lower than 2.0:
Robert Small 1.9
Students with a GPA of 3.5 or higher:
Tom Wang 3.5
When writing the highlow function, take advantage of the fact that the array elements are sorted based on the GPA, so to find all the students with a GPA of equal to or higher than the minimum GPA, it doesn't make sense to start from the first element in the array. Instead you can start from the midpoint. If the midpoint is lower than the minimum GPA, you can increment the index until the midpoint is no longer smaller and then all the GPA's from that point on will be larger and part of the high GPA's. For low GPA's of course, you'd want to start from the beginning of the array and compare and store each that's lower than the maximum until they are no longer lower.
Functions you must write for this assignment (in addition to main):
initialize, read, display, sort_name, sort_gpa, search-name, search_gpa, stats, highlow.
Upload your cpp and exe files using the Browse and Upload buttons below and click Finish once both have been uploaded to the site.*/
I debugged it for you.
The problem is in your stringToCharArray(string s, char c[]).
My index i arrived to 104 before getting "segmentation fault". Since all your strings have length 50 you are clearly going out of bounds.
Another problem is in srtstr that returns NULL, but this is related to the first problem.
A quick look to your sort_name and InsertItem didn't show up anything wrong, at least in the field of "segmentation error", since it's not so clear what you are trying to do, but at least you are performing the right index checks.
I have an assignment that simulates a dice game. As part of the program, the user enters the number of dice to roll and the number of times to roll them. If the user rolls 4 dice, the program should sum the 4 values, store the result in an array, then redo the program the number times defined by the user. The main code and the function prototypes were defined by our tutor and cannot be amended. We have to write the function.
In Step 3 of the main, there are two for loops. The inner for loop calls the function in question. A 2D array rollSums[][] is assigned to the result of the function. This array is to be used in another function. I can't figure out how to populate the 2D array correctly from the function. The code and my attempt at the function is below:
#include <iostream>
#include <iomanip>
#include <cstdlib> // needed for functions srand() and rand()
#include <ctime> // needed for function time()
#include <cmath> // needed for sqrt()
using namespace std;
const int MAXNUMTOROLL=10;
const int MAXROLLS=100;
int rollDice(int diceVals[], int numToRoll);
int main()
{
int sum;
int rollSums[MAXNUMTOROLL][MAXROLLS];
int diceVals[MAXROLLS];
double mean[MAXNUMTOROLL], std[MAXNUMTOROLL];
int numToRoll, numRolls;
srand(time(NULL));
// STEP 1: Ask user to input the maximum number of dice to use:
cout << "Please enter the maximum number of dice to use:" << endl;
do
{
cin >> numToRoll;
} while (numToRoll < 0 || numToRoll > MAXNUMTOROLL);
cout << "Please enter the number of rolls:" << endl;
// STEP 2: Ask user to input the number of rolls to carry out:
do
{
cin >> numRolls;
} while (numRolls < 0 || numRolls > MAXROLLS);
// STEP 3: For k=1 to numToRoll, simulated numRolls rolls of the dice
// and store the sum of the numbers rolled in the array rollSums[][]
for (int k=1;k<=numToRoll;k++)
{
for (int i=0;i<numRolls;i++)
{
rollSums[k-1][i] = rollDice(diceVals, k);
}
}
return 0;
}
int rollDice(int diceVals[], int numToRoll) //function simulating throwing of dice
{
int sum=0;
int i=0;
for(i=0;i<numToRoll;i++)
{
diceVals[i]=1+rand()%6;
sum=sum+diceVals[i];
}
return sum;
}
adohertyd, see my comments in the code sample:
#include <iostream>
#include <iomanip>
#include <cstdlib> // needed for functions srand() and rand()
#include <ctime> // needed for function time()
#include <cmath> // needed for sqrt()
using namespace std;
const int MAXNUMTOROLL=10;
const int MAXROLLS=100;
const bool show_debug = true;
int rollDice(int diceVals[], int numToRoll);
int main()
{
int roll_Sums[MAXNUMTOROLL];
int diceVals[MAXROLLS];
//double mean[MAXNUMTOROLL], std[MAXNUMTOROLL];
int numDice, numThrows;
//Initialize random number generator with the current time
srand(time(NULL));
// STEP 1: Ask user to input the maximum number of dice to use:
cout << "Please enter the maximum number of dice to use:" << endl;
// STEP 2: Validate number of dice input
do
{
cin >> numDice;
} while (numDice < 0 || numDice > MAXNUMTOROLL);
//STEP 3: Ask user to input the number of times to throw each dice
cout << "Please enter the number of rolls:" << endl;
// STEP 4: Validate number of throws input
do
{
cin >> numThrows;
} while (numThrows < 0 || numThrows > MAXROLLS);
cout << "\n\nThrowing Dice Now...\n\n";
// STEP 5: Roll the dice
//The loop deals with each dice
for (int diceCount = 0; diceCount < numDice; diceCount++)
{
//The function call deals with all the throws per dice
//Note: roll_Sums array didn't need to be two dimensional,
// also, rollDice gets passed diceVals[] by value and the number of throws to execute
roll_Sums[diceCount] = rollDice(diceVals, numThrows);
//Debug output
if(show_debug)
{
//Since roll_Sums is zero based, add one to the visible index so the user doesn't get confused :P
cout << "Roll Sum for dice #" << diceCount + 1 << ": " << roll_Sums[diceCount] << endl << endl;
}
}
return 0;
}
//rollDice() returns the sum of all the dice rolls it performed
int rollDice(int diceVals[], int numToRoll)
{
int sum=0;
for(int i=0;i<numToRoll;i++)
{
//Get your random dice rolls
diceVals[i]=1+rand()%6;
//Debug output
if(show_debug)
{
cout << "Dice Roll # " << i+1 << ": " << diceVals[i] << endl;
}
//Accumulate your value, e.g. "sum"
sum += diceVals[i];
}
return sum;
}