so I am beginner to C++ and I am trying to make a Class that contains functions for getting Data, calculating average sum and dividing them by how much grades there are(5) and the final function is for displaying the data about the student.Here's what I get in the console : Click for image
I would be happy to get some advice from you guys.
Here is the code :
class Students{
int br;
char Name[30];
int fakn,i;
float grades[5],sum;
char spec[25];
public:
void takingdata();
float avarage();
void displaydata();
};
void Students::takingdata(){
cout << "Enter name of the student: "; cin.getline(Name, 20);
cout << "Enter his faculty number: "; cin >> fakn;
cout << "specialty: "; cin.getline(spec, 10);
cout << "Enter grades : ";
for (i = 0; i < 5; i++){
cout << "Enter his grades(5 classes): "; cin >> grades[i];
}
}
float Students::avarage(){
sum = 0;
br = 0;
for (i = 0; i < 5; i++){
sum = sum + grades[i];
}
return sum / 5;
}
void Students::displaydata(){
cout << "Name of student: " << Name;
cout << "Student faculty number: " << fakn;
cout << "Student specialty: " << spec;
for (i = 0; i < 5; i++){
cout << "His " << i << " grade: " << grades[i];
}
cout << "His avarage grade: " << avarage();
}
void main(){
Students in,out;
in.takingdata();
out.displaydata();
_getch();
}
As a result I want the program to display the entered information about the student.
First of all:
Students in,out;
in.takingdata();
out.displaydata();
How is this supposed to work? You have two objects here, writing into the first and reading from the second.
It should be something like:
Students students;
students.takingdata();
students.displaydata();
Still, it's important to understand what really happens in your version of the code. As we have just established, everything you read from std::cin into in is discarded later on. Which bears the question of what exactly you read from out. Let's look at the relevant portion of your class definition again:
int br;
char Name[30];
int fakn,i;
float grades[5],sum;
char spec[25];
All of these member variables are of so-called primitive type. This means, among other things, that if you don't initialize them explictly, they will be left uninitialized. For example, br does not "start at 0". It is, strictly speaking, nothing until you assign it something.
Any attempt to output these uninitialized values yields undefined behaviour. Undefined behaviour means that the C++ language specification "gives up" and does not say what the resulting program should do.
What often happens in practice in a situation like yours here is that your program reads a more or less random value that happened to be at the location in memory represented by the variable, and prints that one. The dangerous thing about this is that it may seem to work correctly for a long while because the memory location just happens to contain a zero value, luring you into thinking that your program is bug-free, and then it suddenly crashes or prints garbage values.
So the obvious first fix we should apply to your code is making sure that all the member variables are initialized. While we do that, I'll also:
Add #include <iostream> on top.
Add std:: in front of all standard-library features (that's good practice).
Change the illegal void main to int main.
Remove the unnecessary _getch call.
Here's the result afer the first iteration of fixes:
#include <iostream>
class Students{
int br;
char Name[30];
int fakn,i;
float grades[5],sum;
char spec[25];
public:
Students() :
br(0),
Name(),
fakn(0),
i(0),
grades(),
sum(0.0),
spec()
{}
void takingdata();
float avarage();
void displaydata();
};
void Students::takingdata(){
std::cout << "Enter name of the student: "; std::cin.getline(Name, 20);
std::cout << "Enter his faculty number: "; std::cin >> fakn;
std::cout << "specialty: "; std::cin.getline(spec, 10);
std::cout << "Enter grades : ";
for (i = 0; i < 5; i++){
std::cout << "Enter his grades(5 classes): "; std::cin >> grades[i];
}
}
float Students::avarage(){
sum = 0;
br = 0;
for (i = 0; i < 5; i++){
sum = sum + grades[i];
}
return sum / 5;
}
void Students::displaydata(){
std::cout << "Name of student: " << Name;
std::cout << "Student faculty number: " << fakn;
std::cout << "Student specialty: " << spec;
for (i = 0; i < 5; i++){
std::cout << "His " << i << " grade: " << grades[i];
}
std::cout << "His avarage grade: " << avarage();
}
int main(){
Students students;
students.takingdata();
students.displaydata();
}
Note: If you use Visual C++, you should read the following about array-member initialization:
https://msdn.microsoft.com/en-us/library/1ywe7hcy.aspx
But that's not yet very satisfactory. Why should a student's name not be longer than 29 characters (your array consists of a maximum of 29 visible characters plus a terminating '\0' for C-style strings)? And why should it take 30 characters in memory when it turns out to be much shorter?
In fact, what happens if you enter more than 29 characters? Let's give it a try:
Enter name of the student: Long name that does not fit any more in 30 characters
Enter his faculty number: specialty: Enter grades : Enter his grades(5 classes): Enter his grades(5 classes): Enter his grades(5 classes): Enter his grades(5 cl
asses): Enter his grades(5 classes): Name of student: Long name that doesStudent faculty number: 0Student specialty: His 0 grade: 0His 1 grade: 0His 2 grade: 0H
is 3 grade: 0His 4 grade: 0His avarage grade: 0
That's not good. std::istream::getline attempts to write more than 30 characters into a 30-element array. This already yields undefined behaviour. Even if it magically stopped after 30 elements, you'd end up with an array without the terminating '\0', so later outputting code would again leave the array's bounds looking for it. In addition to that, all attempts at reading numbers via std::cin fail because the stream contents after the 30th character cannot be interpreted as numbers, leaving the variables it's supposed to write into in their previous state.
As you can see, reading into a fixed-size char array the way you did is an almost hopeless undertaking. Fortunately, C++ does not force you to keep up with all of that. It offers std::string for dynamically sized strings, and a free-standing std::getline function to read safely into them.
Here's the second iteration of fixes. Note that std::string is not a primitive type, so it knows how to correctly initialize itself. I still added the two variables to the initializer list to be consistent with the other members.
#include <iostream>
#include <string>
class Students{
int br;
std::string Name;
int fakn,i;
float grades[5],sum;
std::string spec;
public:
Students() :
br(0),
Name(),
fakn(0),
i(0),
grades(),
sum(0.0),
spec()
{}
void takingdata();
float avarage();
void displaydata();
};
void Students::takingdata(){
std::cout << "Enter name of the student: "; std::getline(std::cin, Name);
std::cout << "Enter his faculty number: "; std::cin >> fakn;
std::cout << "specialty: "; std::getline(std::cin, spec);
std::cout << "Enter grades : ";
for (i = 0; i < 5; i++){
std::cout << "Enter his grades(5 classes): "; std::cin >> grades[i];
}
}
float Students::avarage(){
sum = 0;
br = 0;
for (i = 0; i < 5; i++){
sum = sum + grades[i];
}
return sum / 5;
}
void Students::displaydata(){
std::cout << "Name of student: " << Name;
std::cout << "Student faculty number: " << fakn;
std::cout << "Student specialty: " << spec;
for (i = 0; i < 5; i++){
std::cout << "His " << i << " grade: " << grades[i];
}
std::cout << "His avarage grade: " << avarage();
}
int main(){
Students students;
students.takingdata();
students.displaydata();
}
The program could take a lot more fixes. For example, you will want to replace the float array with std::vector<float>, and also generally use double instead of float.
In short: You should just use more C++ and less C if you want to program in C++.
#include <iostream>
#include <cstdio>
using namespace std;
class Students {
private:
static const int CLASSES = 5;
static const int NAME = 30;
static const int SPEC = 15;
char name[NAME], spec[SPEC];
int fakn;
float grades[CLASSES],sum;
public:
Students();
void takingdata();
void avarage();
void displaydata();
};
//constructor
Students::Students(){
takingdata();
avarage();
displaydata();
}
//user innput
void Students::takingdata(){
cout << "Enter name of the student: ";
cin.getline(name, NAME);
cout << "Enter his faculty number: ";
cin >> fakn;
cin.ignore();
cout << "specialty: ";
cin.getline(spec, SPEC);
printf("\nEnter Grades (%u classes)\n", CLASSES);
for (int i = 0; i < CLASSES; i++){
printf("Grade 0%u: ", i+1);
cin >> grades[i];
}
}
//calculations
void Students::avarage(){
sum = 0;
for (int i = 0; i < CLASSES; i++){
sum = sum + grades[i];
}
sum /= CLASSES;
}
//display
void Students::displaydata(){
printf("\n\nStudent Name: %s\nFaculty Number: %u\nSpecialty: %s\nGrade Average: %f", name, fakn, spec, sum);
for (int i = 0; i < CLASSES; i++){
printf("\nGrade 0%u: %f", i+1, grades[i]);
}
}
//main
int main(){
//all other functions now called in constructor
Students in;
return 0;
}
Related
Structure and DMA. I want to retrieve all the inserted record in decreasing order of cgpa.
Without sorting it give the result as shown below image.
#include<iostream>
#include<string>
using namespace std;
struct student {
string name;
int age;
float cgpa;
};
void main()
{
student *ptr;
int size;
cout << "enter size \n";
cin >> size;
ptr = new student[size];
for (int i = 0; i < size; i++)
{
cout << "enter student " << i + 1 << " name\n";
cin >> ptr[i].name;
cout << "enter student " << i + 1 << " age\n";
cin >> ptr[i].age;
cout << "enter student " << i + 1 << " cgpa\n";
cin >> ptr[i].cgpa;
}
cout << "with out sorting \n";
for (int i = 0; i < size; i++)
{
cout << " NAME\tAGE\tCGPA\n";
cout << ptr[i].name << "\t" << ptr[i].age << "\t" << ptr[i].cgpa << endl;
}
system("pause");
}
[1]: https://i.stack.imgur.com/whP8d.png
"Without sorting" is a bit unclear, but I take that to mean you cannot call std::sort directly or use another explicit sorting routine. That leaves you with choosing a container that stores object in sort order based on a compare function (or overload) you provide. Looking at the Microsoft C++ language conformance table for VS2015, it shows all core language features for C++11 supported -- which would include std::set.
std::set allows you to store a sorted set of unique objects. This means you can take input and store the results in a std::set based a Compare function you provide. Providing a Compare function that will compare the cgpa of each student will then automatically store your student objects based cgpa.
To make std::set available, you simply need to #include<set>. Writing the compare function that can be used to store students based on cgpa simply requires providing an overload for the < operator that takes two of your student objects as arguments and then returns true when the first argument sorts before the second, false otherwise. That can be as simple as:
/* overload of < comparing student by cgpa */
bool operator <(const student& a, const student& b) {
return a.cgpa < b.cgpa;
}
A note: unless you are compiling for a micro-controller or embedded system with no Operating System (called a freestanding environment), void main() is wrong. A standard conforming invocation of main() is either int main(void) or int main (int argc, char **argv) where argc is the argument count and argv your argument vector (technically an array of pointers to null-terminated strings where the next pointer after the last argument is set to NULL as a sentinel) There are other non-standard extensions added by some compilers like char **envp providing a pointer to each of the environment variables.
To declare your set of student you need to provide the type student and the compare function to be used when inserting students into your set. Since you provide an overload for the less-than operator, you can use std::less<> providing one template argument, e.g.
int main(void)
{
/* create std::set of students using std::less for compare */
std::set<student, std::less<const student&>> students {};
And since you are using a container that provides automatic memory management for you, there is no need to know the size (or number of students to enter) before hand. You can simply enter as many students as you need and then press Ctrl+d on Linux or Ctrl+z on Windows to generate a manual EOF signifying your end of input. However you do need to validate every user input by checking the return (stream state) following each input. At minimum you can use:
std::cout << "enter student " << i + 1 << " name\n";
if (!(std::cin >> s.name)) /* validate all input, ctrl + z to end input */
break;
(note: the variable i is only needed to show the student number when you prompt for input, all containers provides the .size() member function that tell you how many objects are contained within.)
When done taking input, you can use a Range-based for loop to iterate over each student in your set outputting the desired information. For example:
std::cout << "\nwith out sorting \n";
for (auto& s : students) { /* output in order of cgpa w/o sorting */
std::cout << " NAME\tAGE\tCGPA\n"
<< s.name << "\t" << s.age << "\t" << s.cgpa << '\n';
}
Putting it altogether, you could do:
#include <iostream>
#include <string>
#include <set>
struct student { /* struct student */
std::string name;
int age;
float cgpa;
};
/* overload of < comparing student by cgpa */
bool operator <(const student& a, const student& b) {
return a.cgpa < b.cgpa;
}
int main(void)
{
/* create std::set of students using std::less for compare */
std::set<student, std::less<const student&>> students {};
for (int i = 0; ; i++) {
student s {}; /* temporary struct to add to set */
std::cout << "enter student " << i + 1 << " name\n";
if (!(std::cin >> s.name)) /* validate all input, ctrl + z to end input */
break;
std::cout << "enter student " << i + 1 << " age\n";
if (!(std::cin >> s.age))
break;
std::cout << "enter student " << i + 1 << " cgpa\n";
if (!(std::cin >> s.cgpa))
break;
students.insert(s); /* insert student in set */
}
std::cout << "\nwith out sorting \n";
for (auto& s : students) { /* output in order of cgpa w/o sorting */
std::cout << " NAME\tAGE\tCGPA\n"
<< s.name << "\t" << s.age << "\t" << s.cgpa << '\n';
}
}
(note: Look at Why is “using namespace std;” considered bad practice?. Developing good habits early is a lot easier that trying to break bad ones later...)
(note 2: you might consider using getline(std::cin, s.name) to take input for the student name so you can handle names with spaces, like Firstname Lastname, e.g. Mickey Mouse, up to you)
Add system("pause"); back in to hold your terminal window open as needed.
Example Use/Output
Now just enter the student data for as many students as you like and then terminate input by generating a manual EOF as described above, e.g.
$ ./bin/set_student_grades
enter student 1 name
gates
enter student 1 age
20
enter student 1 cgpa
2.12
enter student 2 name
della
enter student 2 age
21
enter student 2 cgpa
2.00
enter student 3 name
jim
enter student 3 age
30
enter student 3 cgpa
3.12
enter student 4 name
with out sorting
NAME AGE CGPA
della 21 2
NAME AGE CGPA
gates 20 2.12
NAME AGE CGPA
jim 30 3.12
This provides a way to store and provide the student data in order of cgpa without an explicit sort. Of course std::set does that for you, but if avoiding an explicit sort was the intent of your program, this is very good option. Let me know if you have further questions.
#include<iostream>
#include<string>
using namespace std;
struct student {
string name;
int age;
float cgpa;
};
void main() {
student *ptr;
int size;
cout << "enter size \n"; cin >> size;
ptr = new student[size];
for (int i = 0; i < size; i++)
{
cout << "enter student " << i + 1 << " name\n";
cin >> ptr[i].name;
cout << "enter student " << i + 1 << " age\n";
cin >> ptr[i].age;
cout << "enter student " << i + 1 << " cgpa\n";
cin >> ptr[i].cgpa;
}
string temp1; int temp2; float temp3;
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
if (ptr[i].cgpa < ptr[j].cgpa)
{
temp1 = ptr[j].name;
ptr[j].name = ptr[i].name;
ptr[i].name = temp1;
temp2 = ptr[j].age;
ptr[j].age = ptr[i].age;
ptr[i].age = temp2;
temp3 = ptr[j].cgpa;
ptr[j].cgpa = ptr[i].cgpa;
ptr[i].cgpa = temp3;
}
}
}
for (int i = 0; i < size; i++) {
cout << " NAME\tAGE\tCGPA\n";
cout << ptr[i].name << "\t" << ptr[i].age << "\t" << ptr[i].cgpa << endl;
}
delete[] ptr;
system("pause");
}
I am trying to do some stuff with C++ and i am new in it :)
I have tried 1 program of class that gets the student details and print the output of it.
#include <iostream>
using namespace std;
#define MAX 10
class student
{
private:
char name[30];
int rollNo;
int total;
float perc;
public:
//member function to get student's details
void getDetails(void);
//member function to print student's details
void putDetails(void);
};
//member function definition, outside of the class
void student::getDetails(void){
cout << "Enter name: " ;
cin >> name;
cout << "Enter roll number: ";
cin >> rollNo;
cout << "Enter total marks outof 500: ";
cin >> total;
perc=(float)total/500*100;
}
//member function definition, outside of the class
void student::putDetails(void) {
cout << "Student details:\n";
cout << "Name:"<< name << ",Roll Number:" << rollNo << ",Total:" << total << ",Percentage:" << perc;
}
int main()
{
student std[MAX]; //array of objects creation
int n,loop;
cout << "Enter total number of students: ";
cin >> n;
for(loop=0;loop< n; loop++){
cout << "Enter details of student " << loop+1 << ":\n";
std[loop].getDetails();
}
cout << endl;
for(loop=0;loop< n; loop++) {
cout << "Details of student " << (loop+1) << ":\n";
std[loop].putDetails();
}
return 0;
}
Its very basic code and works fine and I am able to give inputs and print the output.
Now I want to add new Student object at runtime using Dynamic memory allocation and want to add that object in the existing array of object (So that I can get the highest, lowest marks of any student)
I know I need to use new operator for this.
But I am not sure what could be the best way to write this solution.
Any help will be highly appreciated.
Thanks!
IMO, The best way to do this using dynamic memory is by using std::unique_ptr or std::shared_ptr (it actually depends on the requirement).
Here is one example of usage of unique_ptr:
using StudentPtr = std::unique_ptr<student>;
int main() {
std::vector<StudentPtr> studentDetails;
int n;
cout << "Enter the number of students: ";
cin >> n;
studentDetails.resize(n);
for (auto &s: studentDetails) {
s = StudentPtr(new student);
s->getDetails();
}
return 0;
}
For getting minimum and maximum, you may use min_element and max_element provided by STL respectively.
Recently in my c++ class we have learned about pointers and classes.
I'm trying to make a program that has a class Student, which we will point to give each student a name and test score.
After entering both name and test score, they are sorted and then listed in order of highest to lowest.
I believe all my syntax to be correct, however I am still learning. The problem I am having is that the first time I use my class I get an uninitialized local variable error, any help on how to fix this?
#include "stdafx.h"
#include <iostream>
#include <string>
#include <array>
using namespace std;
class Student {
private:
double score;
string name;
public:
void setScore(double a) {
score = a;
}
double getScore() {
return score;
}
void setName(string b) {
name = b;
}
string getName() {
return name;
}
};
void sorting(Student*, int);
int main()
{
Student *students;
string name;
int score;
int *count;
count = new int;
cout << "How many students? ";
cin >> *count;
while (*count <= 0) {
cout << "ERROR: The number of students must be greater than 0.\n";
cin >> *count;
}
for (int i = 0; i < *count; i++) {
cout << "Please enter the students name: ";
cin >> name;
students[i].setName(name);
cout << "Please enter " << students[i].getName() << "'s score: ";
cin >> score;
while (score < 0) {
cout << "ERROR: Score must be a positive number.\n";
cin >> score;
}
students[i].setScore(score);
}
sorting(students, *count);
for (int i = 0; i < *count; i++) {
cout << students[i].getName() << ": " << students[i].getScore() << endl;
}
system("PAUSE");
return 0;
}
void sorting(Student *s, int size) {
for (int i = 0; i < size; i++) {
for (int j = i; j < size; j++) {
if (s[j].getScore() > s[(j + 1)].getScore()) {
int tmp = s[(j + 1)].getScore();
s[(j + 1)].setScore(s[j].getScore());
s[j].setScore(tmp);
string tmp1 = s[(j + 1)].getName();
s[(j + 1)].setName(s[j].getName());
s[j].setName(tmp1);
}
}
}
}
First off, your Student class can be simplified to this:
struct Student {
double score;
std::string name;
};
Because the accessors do absolutely nothing. I've also added the std:: prefix because using namespace std is considered a bad practice.
Now, instead of using the pointer to store the students, include vector and use that:
std::cout << "How many students? ";
int count;
std::cin >> count;
std::vector<Student> students(count);
The loading routine can also be simplified given the absence of accesors:
for (auto& student : students) {
std::cout << "Please enter the students name: ";
std::cin >> student.name;
std::cout << "Please enter " << student.name << "'s score: ";
std::cin >> student.score;
while (score < 0) {
std::cout << "ERROR: Score must be a positive number.\n";
std::cin >> student.score;
}
}
And actually once you have that, you could just put it in istream& operator>>(istream&, Student&) and reduce it to:
std::copy_n(std::istream_iterator<Student>(std::cin), students.size(), students.begin());
No need now for temporary variables anymore (and even if you want to use them, they should be defined just before the use, so inside of the loop).
The last thing is your sorting routine. First off, there's std::sort that you can use instead if you simply provide a comparator:
std::sort(
begin(students),
end(students),
[](Student const& a, Student const& b) { return b.score < a.score; }
);
If you insist on writing the sorting routine yourself, at least use std::swap.
I've come across a little problem, how do I print the winning candidate's name? See the instructions here are, input five names, their number of votes and percentage of votes, whoever has the highest wins. I don't know if I did my code right, but it works.. well except for the name part. I've tried everything from a lot of for loops to transfer the array or what.
I'm almost done with the code.
Here's the code
#include <iostream>
#include <stdio.h>
using namespace std;
int main()
{
char candidates[50];
int votes[5]={0};
float percent[5]={0};
int a,b,c,d,e,i;
int maxx;
int champ=0;
char winner[50];
cout << "Enter the candidates' last names: ";
cout << endl;
for(a=1;a<=5;a++)
{
cout << a << ". ";
cin >> candidates;
}
cout << endl;
cout << "Enter their number of votes: " << endl;
for(b=1;b<=5;b++)
{
cout << b << ". ";
cin >> votes[b];
}
cout << endl;
cout << "percentage of votes: " << endl;
for(c=1;c<=5;c++)
{
cout << c << ". ";
percent[c]=votes[c]*0.2;
printf("%.2f\n", percent[c]);
}
cout <<"Candidates\t\tVotes\t\t% of Votes" << endl;
for(int k=1;k<=5;k++)
{
cout << candidates[k] << "\t\t\t" << votes[k] << "\t\t\t";
printf("%.2f\n", percent[k]);
}
maxx=percent[0];
for(d=1;d<=5;d++)
{
if(maxx<percent[d]);
{
//what happens here?
}
}
return 0;
}
You should keep a 2d array of characters or array of string for storing candidate names instead of a 1-d array.
char candidates[5][10]; //
for(int i = 0; i < 5; i++)
{
cin >> candidates[i];
}
Then keep a variable to store index for winning candidate
int winIndex = 0;
int winPercent = 0;
for(int i = 0; i < 5; i++)
{
if(percent[i] > winPercent)
{
winPercent = percent;
winIndex = i;
}
}
Finally print name of winning candidate;
cout << candidates[winIndex];
In object oriented approach, you may create a class with following information
class Candidate
{
string name;
int votes;
float percent;
};
Use string candidates[50]; instead of char candidates[50];
then cin >> candidates[a];
I am working on a grade book project that has 5 students that I want to read the names in for and then with an inner loop grab 4 grades for each student. Something is not working on this loop. This what I am getting:
Please enter the name for student 1: Dave
Please enter the grade number 1 for Dave: 100
Please enter the grade number 2 for Dave: 100
Please enter the grade number 3 for Dave: 100
Please enter the grade number 4 for Dave: 10
Please enter the name for student 2: James
Please enter the grade number 5 for James: 100
Please enter the name for student 3: Sam
Please enter the grade number 5 for Sam: 100
Please enter the name for student 4: Jack
Please enter the grade number 5 for Jack: 100
Please enter the name for student 5: Mike
Please enter the grade number 5 for Mike: 100
It should grab 4 grades before it jumps to the next student. I have not been able to figure this out for the last couple hours. Here is the code I have so far:
#include <iostream>
#include <string>
using namespace std;
const int STUDENTS = 5; //holds how many students we have
const int SCORES = 4;
void getNames(string names[], double student1[SCORES], double student2[SCORES],
double student3[SCORES], double student4[SCORES], double student5[SCORES], int SCORES, int STUDENTS);
int main()
{
string names[STUDENTS] = {""};
char grades[STUDENTS] = {""};
double student1[SCORES] = {0};
double student2[SCORES] = {0};
double student3[SCORES] = {0};
double student4[SCORES] = {0};
double student5[SCORES] = {0};
getNames(names, student1, student2, student3, student4, student5, SCORES, STUDENTS);
// Make sure we place the end message on a new line
cout << endl;
// The following is system dependent. It will only work on Windows
system("PAUSE");
return 0;
}
void getNames(string names[], double student1[SCORES], double student2[SCORES],
double student3[SCORES], double student4[SCORES], double student5[SCORES], int SCORES, int STUDENTS)
{
for (int i = 0; i < STUDENTS; i++)
{
cout << "Please enter the name for student " << i+1 << ": ";
cin >> names[i];
cout << endl;
if (i == 0)
{
int count1 = 0;
for (count1; count1 < SCORES; count1++)
{
cout << "Please enter the grade number " << count1+1 << " for " << names[i] <<": ";
cin >> student1[count1];
cout << endl;
}
}
else if (i == 1)
{
int count2 = 0;
for (count2; count2 < SCORES; count2++);
{
cout << "Please enter the grade number " << count2+1 << " for " << names[i] <<": ";
cin >> student2[count2];
cout << endl;
}
}
else if (i == 2)
{
int count3 = 0;
for (count3; count3 < SCORES; count3++);
{
cout << "Please enter the grade number " << count3+1 << " for " << names[i] <<": ";
cin >> student3[count3];
cout << endl;
}
}
else if (i == 3)
{
int count4 = 0;
for (count4; count4 < SCORES; count4++);
{
cout << "Please enter the grade number " << count4+1 << " for " << names[i] <<": ";
cin >> student4[count4];
cout << endl;
}
}
else
{
int count5 = 0;
for (count5; count5 < SCORES; count5++);
{
cout << "Please enter the grade number " << count5+1 << " for " << names[i] <<": ";
cin >> student5[count5];
cout << endl;
}
}
}
}
Thanks for any help on this!
There's some pretty rough stuff going on in here, but the problem is that you have a semi-colon on all your inner loops except the first one:
for (count2; count2 < SCORES; count2++);
Remove the semi-colon, and the stuff in the braces will become part of the loop.
I'm going to suggest you make your code a little tidier and less error-prone by chucking all those function arguments into their own array when you enter the function, like this:
double *scores[5] = { student1, student2, student3, student4, student5 };
Then you take OUT all that repetition - the copy/paste is what caused your problems to begin with:
for (int i = 0; i < STUDENTS; i++)
{
cout << "Please enter the name for student " << i+1 << ": ";
cin >> names[i];
cout << endl;
for (int s = 0; s < SCORES; s++)
{
cout << "Please enter the grade number " << s+1 << " for " << names[i] <<": ";
cin >> scores[i][s];
cout << endl;
}
}
Why can't you use two nested loops like
for (int studix=0, stduix<STUDENTS; studix++) {
//...
for (int gradix=0; gradix<SCORE; gradix++) {
//...
}
//....
}
BTW, the condition could be a more complex one, e.g. with the internal loop being
bool goodgrade=true;
for (int gradix=0; goodgrade && gradix<SCORE; gradix++) {
// you could modify goodgrade or use break; inside the loop
}
Don't forget the possible use of continue and break inside a loop.
And please, take time to read some good C++ programming book
Building on Basile's answer and my comments:
int main()
{
string names[STUDENTS] = {""};
char grades[STUDENTS] = {""};
double student1[SCORES] = {0};
double student2[SCORES] = {0};
double student3[SCORES] = {0};
double student4[SCORES] = {0};
double student5[SCORES] = {0};
double *gradeArray[STUDENTS];
gradeArray[0] = student1;
gradeArray[1] = student2;
gradeArray[2] = student3;
gradeArray[3] = student4;
gradeArray[4] = student5;
for (int studix=0, stduix<STUDENTS; studix++) {
// get the name of the student
for (int gradix=0; gradix<SCORE; gradix++) {
// put the grades in gradeArray[studix][gradix]...
}
//....
}
Yes, I know about 2 D arrays, but I am trying to make explicit how this can be done with "five individual arrays". Clumsy, but I believe this works.