how to pass an array through to another function? c++ - c++

so i am making a program that takes student data as objects and prints it, i am trying to store the data as an array so each student is a element in the array, i am having issues with printing the data though as i cannot pass the array into the print function, can anyone help? when i try and compile i get "studentarray: arrays of references are illegal". sorry if this is a stupid question i am new to coding, thankyou!

You wrote student printstudent(student & studentarray); which looks more like a deceleration than a function call.
I'm guessing you wanted to write printstudent(studentarray)?
Your error is caused by declaring printstudent(student& studentarray[10]) , which declares the function argument to be an array of 10 student& i.e. references to students, which the c++ standard forbids:
There shall be no references to references, no arrays of references, and no pointers to references.
Some more details on why can be found here: Why are arrays of references illegal?

After a bit of refactoring and fixing bugs, here it is:
#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
class Student
{
public:
std::string name;
std::string email;
std::string number;
int grade1, grade2, grade3, grade4, totalGrade;
float percentage1, percentage2, percentage3, percentage4, totalPercentage;
public:
static void addStudent( std::vector<Student>& students )
{
std::cout << "\nEnter the number of students: ";
std::size_t count { };
std::cin >> count;
std::cout << '\n';
for ( std::size_t idx { }; idx < count; ++idx )
{
std::cout << "Enter the details of student #" << idx + 1 << ":\n";
students.resize( students.size( ) + 1 );
students.back( ).inputStudentDetails( );
std::cout << '\n';
}
std::cout << '\n';
}
void inputStudentDetails( )
{
std::cout << "Enter Student name: ";
std::cin >> name;
std::cout << "Enter student number: ";
std::cin >> number;
std::cout << "Enter student email: ";
std::cin >> email;
std::cout << "Enter grade for test1: ";
std::cin >> grade1;
std::cout << "Enter grade for test2: ";
std::cin >> grade2;
std::cout << "Enter grade for test3: ";
std::cin >> grade3;
std::cout << "Enter grade for test4: ";
std::cin >> grade4;
percentage1 = static_cast<float>( grade1 );
percentage2 = static_cast<float>( grade2 );
percentage3 = static_cast<float>( grade3 );
percentage4 = static_cast<float>( grade4 );
totalPercentage = percentage1 + percentage2 + percentage3 + percentage4;
}
void printStudentDetails( ) const
{
std::cout << "Student Name: " << name << "\nStudent Number: " << number
<< "\nStudent email: " << email << "\ngrade1: " << grade1
<< "\ngrade2: " << grade2 << "\ngrade3: " << grade3
<< "\ngrade4: " << grade4 << "\ntotal " << totalPercentage << " out of 400\n";
}
static void printAllStudentsDetails( const std::vector<Student>& students )
{
std::size_t idx { };
for ( const Student& stud : students )
{
std::cout << "\nDetails of student #" << ++idx << ":\n";
stud.printStudentDetails( );
std::cout << std::setfill( '-' ) << std::setw( 28 ) << '\n';
}
}
};
int main( )
{
std::vector<Student> students;
while ( true )
{
std::cout << "\t\tMENU\n" << std::setfill( '_' ) << std::setw( 36 ) << "\n\n";
std::cout << "1: Enter student details\n";
std::cout << "2: Display all students' details\n";
std::cout << "3: Exit the Application\n";
char select { };
std::cin >> select;
switch ( select )
{
case '1' : Student::addStudent( students ); break;
case '2' : Student::printAllStudentsDetails( students ); break;
case '3' : return 0;
default : std::cout << "Invalid Input!\n";
}
}
}

Related

How to set up a number of objects

void Dog::readDog()
{
cout << "Name: ";
cin >> this->name;
cout << "height: ";
cin >> this->height;
cout << "weight: ";
cin >> this->weight;
cout << "Color: ";
cin >> this->color;
}
void Dog::printDog()
{
cout << "Name: " << this->name << endl;
cout << "Height: " << this->height << endl;
cout << "Weight: " << this->weight << endl;
cout << "Color: " << this->color << endl;
}
int main() {
Dog dogs;
int n;
cout << "Number of dogs to introduce: ";
cin >> n;
dogs.readDog();
dogs.printDog();
}
this is a part of my code and i have a little problem because i forgot how to set up a number of dogs that i want to introduce in program, e.g. i want 3 dogs : Max, Rex, Terry. My program read and print just one dog
You can use a std::vector for creating a container that will contain n number of Dog objects as shown below:
#include <iostream>
#include <vector>
#include <string>
class Dog
{
public:
void readDog();
void printDog();
private:
std::string name, color;
double height, weight;
};
void Dog::readDog()
{
std::cout << "Name: ";
std::cin >> this->name;
std::cout << "height: ";
std::cin >> this->height;
std::cout << "weight: ";
std::cin >> this->weight;
std::cout << "Color: ";
std::cin >> this->color;
}
void Dog::printDog()
{
std::cout << "Name: " << this->name << std::endl;
std::cout << "Height: " << this->height << std::endl;
std::cout << "Weight: " << this->weight << std::endl;
std::cout << "Color: " << this->color << std::endl;
}
int main() {
Dog dogs;
int n;
std::cout << "Number of dogs to introduce: ";
std::cin >> n;
std::vector<Dog> vecDogs(n); //create a vector (of size n) of Dog objects
for(int i = 0; i < n; ++i)
{
vecDogs.at(i).readDog();
vecDogs.at(i).printDog();
}
}
std::vector is a variable size container which means you can use it to have n number of Dog objects, where n need not be a constant expression.
The output of the above program can be seen here.

Why won't Xcode (10.1) realize this class? What am I doing wrong

Basically trying to just run this program for extra learning, Xcode won't understand that I have written a class, and wont implement it. Really confused and need some guidance.
When I run the code only the main method is implemented, nothing else works...
#include <iostream>
using namespace std;
class students {
int id;
char name[20];
int s1;
int s2;
int s3;
public:
void getData() {
cout << "Enter the ID " << endl;
cin >> id;
cout << "Enter the name " << endl;
cin >> name;
cout << "Enter the grade in subject 1 " << endl;
cin >> s1;
cout << "Enter the grade in subject 2 " << endl;
cin >> s2;
cout << "Enter the grade in subject 3 " << endl;
cin >> s3;
}
void putData() {
cout << id << " " << name << " " << s1 << " " << s2 << " " << s3 << endl;
}
};
int main () {
students s[20];
int i, n; //i is for the for loop, n for number of students
cout << "Enter the number of students " << endl;
cin >> n;
for (i=0;i>n;i++)
{
s[i].getData();
}
for (i=0;i>n;i++)
{
s[i].putData();
}
return 0;
}

How to use struct members in a struct's member function?

So the purpose of the program is to Create an array of 3 people, allow the user to populate the data in a for loop, ensure that the results are capitalized, and output the results.
These new projects instructions were to
1. Rewrite capitalize() as a method within the structure.
2. Rewrite printPerson() as a method within the structure
The program itself works just fine, it's just not in the format that my professor wanted. He said the point of it is to not use any arguments but again, I don't know what he means. I just started programming a few months ago and even though I'm trying I don't have a strong knowledge of the terminology.
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
struct Person {
string firstName;
string middleName;
string lastName;
int age;
string gender;
void capitalize(Person &arg);
void printPerson(Person arg);
};
Pretty sure these are the methods right here, but I'm not sure if the (person &arg) and (person arg) are the arguments itself or if they are parameters. I thought it was the "arg" part but I can't find a way to get the program to run without them as I'm pretty sure I need the & of operator to modify the information.
int main(void) {
Person myPerson;
Person a[3];
const int size = 5;
for (int i = 0; i <= 2; i++) {
cout << "What is First Name #" << i + 1 << "? ";
getline(cin, a[i].firstName);
cout << "What is Middle Name #" << i + 1 << "? ";
getline(cin, a[i].middleName);
cout << "What is Last Name #" << i + 1 << "? ";
getline(cin, a[i].lastName);
cout << "Age #" << i + 1 << "? ";
cin >> a[i].age;
cin.ignore();
cout << "Male or Female #" << i + 1 << "? ";
getline(cin, a[i].gender);
cout << endl;
}
for (int i = 0; i <= 2; i++) {
myPerson.capitalize(a[i]);
cout << "PERSON #" << i + 1 << endl;
cout << "~~~~~~~~~~~~~~~" << endl;
myPerson.printPerson(a[i]);
}
system("pause");
return 0;
}
Along with that, I don't know how to manipulate the functions to work without the "parameters/arguments" (I'm not sure the difference at this point) or without the "arg"
void Person::capitalize(Person &arg) {
transform(arg.firstName.begin(), arg.firstName.end(), arg.firstName.begin(), ::toupper);
transform(arg.middleName.begin(), arg.middleName.end(), arg.middleName.begin(), ::toupper);
transform(arg.lastName.begin(), arg.lastName.end(), arg.lastName.begin(), ::toupper);
}
void Person::printPerson(Person arg) {
cout << "\nFirst Name: " << arg.firstName << endl;
cout << "\nMiddle Name: " << arg.middleName << endl;
cout << "\nLast Name: " << arg.lastName << endl;
cout << "\nAge: " << arg.age << endl;
cout << "\nGender: " << arg.gender << endl;
cout << "\n\n";
}
The capitalize and the printPerson are now members (usually called methods) of the struct Person. This means that they operate on the member variables of an Person instance. Like this, you can just access all the classes members in these methods. See the following code. I also completed it with a constructor and made it slightly more readable.
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
struct Person {
public:
Person();
void readFromUserInput();
void capitalize();
void print();
public:
string firstName;
string middleName;
string lastName;
int age;
string gender;
};
Person::Person() :
firstName(""),
middleName(""),
lastName(""),
age(0),
gender("")
{
}
void Person::readFromUserInput()
{
cout << "What is the First Name ? ";
getline(cin, firstName);
cout << "What is Middle Name ? ";
getline(cin, middleName);
cout << "What is Last Name ? ";
getline(cin, lastName);
cout << "Age ? ";
cin >> age;
cin.ignore();
cout << "Male or Female ? ";
getline(cin, gender);
}
void Person::capitalize()
{
transform(firstName.begin(), firstName.end(), firstName.begin(), ::toupper);
transform(middleName.begin(), middleName.end(), middleName.begin(), ::toupper);
transform(lastName.begin(), lastName.end(), lastName.begin(), ::toupper);
}
void Person::print()
{
cout << "\nFirst Name: " << firstName << endl;
cout << "\nMiddle Name: " << middleName << endl;
cout << "\nLast Name: " << lastName << endl;
cout << "\nAge: " << age << endl;
cout << "\nGender: " << gender << endl;
cout << "\n\n";
}
int main(void)
{
const int NUM_PERSONS = 3;
Person a[NUM_PERSONS];
for (int i = 0; i < NUM_PERSONS; i++)
{
cout << "### " << (i + 1) << ". User:" << endl;
a[i].readFromUserInput();
cout << endl;
}
for (int i = 0; i < NUM_PERSONS; i++)
{
a[i].capitalize();
cout << "PERSON #" << i + 1 << endl;
cout << "~~~~~~~~~~~~~~~" << endl;
a[i].print();
}
system("pause");
return 0;
}

Error: ld returned 1 exit status June 2015

I need help understanding the [Error] id return 1 exit status due to 2 undefined references: getGrades() and getAverage(). I was issued DEV C++ and knocked out the syntax errors with mild frustration but these "linking" errors are still giving me a hard time. This is the most recent update of the code, if anyone could help me understand these linking errors that would be great.
Compiler - Dev C++
Windows 7
Code:
#include <iostream>
#include <iomanip>
#include <string>
#include <sstream>
using namespace std;
// Function declarations
string getStudentName();
string getWork();
int getGrades();
double getAverage();
int main()
{
string studentName, work[3];
int grades[3];
double average;
// Get the name of the student
studentName = getStudentName();
// Get the work
work[3] = getWork();
// Get the grades
grades[3] = getGrades();
// Get the average
average = getAverage();
// Dynamic spacing for grades
ostringstream ss;
int gradesLength = ss.str().length();
ss <<setprecision(0) << fixed << showpoint;
ss << grades;
cout << "\n the average for " << studentName << " is: " << average << endl;
cout << "The grades for " << studentName << " are: " << endl;
cout << setw(30) << work[0] << ": " << setw(gradesLength) << grades[0] << endl;
cout << setw(30) << work[1] << ": " << setw(gradesLength) << grades[1] << endl;
cout << setw(30) << work[2] << ": " << setw(gradesLength) << grades[2] << "\n\n\n";
cout << "You have completed the program: \n";
return 0;
}
// Student Name
string getStudentName()
{
string name;
cout << "Enter students full name: ";
getline(cin, name);
return name;
}
// Assignments
string getWork()
{
string work[3];
cout << "\nEnter the name of each assignment \n";
cout << "First assignment: ";
getline (cin, work[0]);
cout << "Second assignment: ";
getline (cin, work[1]);
cout << "Third assignment: ";
getline (cin, work[2]);
return work[3];
}
// Grades
int getGrades(string work[3])
{
int grades[3];
cout << "\nEnter the grade for " << work[0] << ": ";
cin >> grades[0];
cout << "Enter the grade for " << work[1] << ": ";
cin >> grades[1];
cout << "Enter the grade for " << work[2] << ": ";
cin >> grades[2];
return grades[3];
}
// Math
double getAverage(int grades[3])
{
double average;
average = (grades[0] + grades[1] + grades[2]) / 3.0f;
return average;
}

How to put variables into an array

I am making a Basketball Scoreboard that can determine the winner of the game in each quarter and the the main game.
How can i store the values of my variables in an array?
I want to put the values of "Q1teamOne, Q2teamOne, Q3teamOne, Q4teamOne" in an array and also the values of "Q1teamTwo, Q2teamTwo, Q3teamTwo ,Q4teamTwo" or make them elements of an array.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string Team1;
string Team2;
double OTscore1;
double OTscore2;
int Q1teamOne, Q2teamOne, Q3teamOne, Q4teamOne;
int Q1teamTwo, Q2teamTwo, Q3teamTwo ,Q4teamTwo;
int Q2TeamOneTotal, Q3TeamOneTotal, Q4TeamOneTotal;
int Q2TeamTwoTotal, Q3TeamTwoTotal, Q4TeamTwoTotal;
double teamOneScore[4];
double teamTwoScore[4];
int index;
double sumOne, sumTwo;
cout << "BASKETBALL SCOREBOARD:\n" << endl;
cout << "Enter Team 1 name: ";
getline (cin, Team1);
cout << "Enter Team 2 name: ";
getline (cin, Team2);
//FIRST QUARTER
cout << "\nQUARTER 1:\n\n";
cout << "Team " << Team1 << " Score: ";
cin >> Q1teamOne;
cout << "Team " << Team2 << " Score: ";
cin >> Q1teamTwo;
if (Q1teamOne > Q1teamTwo)
{
cout <<"****" << "Team " << Team1 << " is Leading.****\n\n";
}
else if (Q1teamOne < Q1teamTwo)
{
cout <<"****" << Team2 << " is Leading.****\n\n";
}
else if (Q1teamOne = Q1teamTwo)
{
cout <<"****We Have a Tie!!****\n\n";
}
//SECOND QUARTER
cout << "\nQUARTER 2:\n\n";
cout << "Team " << Team1 << " Score: ";
cin >> Q2teamOne;
Q2TeamOneTotal = Q1teamOne + Q2teamOne;
cout <<"Total Score: "<< Q2TeamOneTotal <<endl;;
cout << "Team " << Team2 << " Score: ";
cin >> Q2teamTwo;
Q2TeamTwoTotal = Q1teamTwo + Q2teamTwo;
cout <<"Total Score: " << Q2TeamTwoTotal;
if (Q2TeamOneTotal > Q2TeamTwoTotal)
{
cout <<"\n****" << Team1 << " is Leading.****\n\n";
}
else if (Q2TeamOneTotal < Q2TeamTwoTotal)
{
cout <<"\n****" << Team2 << " is Leading.****\n\n";
}
else if (Q2TeamOneTotal = Q2TeamTwoTotal)
{
cout <<"\n****We Have a Tie!!****\n\n";
}
//THIRD QUARTER
cout << "\nQUARTER 3:\n\n";
cout << "Team " << Team1 << " Score: ";
cin >> Q3teamOne;
Q3TeamOneTotal = Q1teamOne + Q2teamOne + Q3teamOne;
cout <<"Total Score: "<< Q3TeamOneTotal <<endl;;
cout << "Team " << Team2 << " Score: ";
cin >> Q3teamTwo;
Q3TeamTwoTotal = Q1teamTwo + Q2teamTwo + Q3teamTwo;
cout <<"Total Score: " << Q3TeamTwoTotal;
if (Q3TeamOneTotal > Q3TeamTwoTotal)
{
cout <<"\n****" << Team1 << " is Leading.****\n\n";
}
else if (Q3TeamOneTotal < Q3TeamTwoTotal)
{
cout <<"\n****" << Team2 << " is Leading.****\n\n";
}
else if (Q3TeamOneTotal = Q3TeamTwoTotal)
{
cout <<"\n****We Have a Tie!!****\n\n";
}
//FOURTH QUARTER
cout << "\nQUARTER 4:\n\n";
cout << "Team " << Team1 << " Score: ";
cin >> Q4teamOne;
Q4TeamOneTotal = Q1teamOne + Q2teamOne + Q3teamOne + Q4teamOne;
cout <<"Total Score: "<< Q4TeamOneTotal <<endl;
cout << "Team " << Team2 << " Score: ";
cin >> Q4teamTwo;
Q4TeamTwoTotal = Q1teamTwo + Q2teamTwo + Q3teamTwo + Q4teamTwo;
cout <<"Total Score: " << Q4TeamTwoTotal;
if (Q4TeamOneTotal > Q4TeamTwoTotal)
{
cout <<"\n****" << Team1 << " is Leading.****\n\n";
}
else if (Q4TeamOneTotal < Q4TeamTwoTotal)
{
cout <<"\n****" << Team2 << " is Leading.****\n\n";
}
else if (Q4TeamOneTotal = Q4TeamTwoTotal)
{
cout <<"\n****We Have a Tie!!****\n\n";
}
For example
#include <functional>
//...
std::reference_wrapper<int> teamOne[] = { Q1teamOne, Q2teamOne, Q3teamOne, Q4teamOne };
std::reference_wrapper<int> teamTwo[] = { Q1teamTwo, Q2teamTwo, Q3teamTwo ,Q4teamTwo };
Here is a demonstrative program
#include <iostream>
#include <functional>
int main()
{
int Q1teamOne, Q2teamOne, Q3teamOne, Q4teamOne;
std::reference_wrapper<int> teamOne[] =
{
Q1teamOne, Q2teamOne, Q3teamOne, Q4teamOne
};
int i = 0;
for ( auto &x : teamOne ) x.get() = i++;
for ( const auto &x : teamOne ) std::cout << x << ' ';
std::cout << std::endl;
return 0;
}
The program output is
0 1 2 3
Or if the link between the original values and the array is not need then you could write simply
double teamOneScore[] = { Q1teamOne, Q2teamOne, Q3teamOne, Q4teamOne };
Also you could use initializer list in the range based for statement without declaring any array. For example
for ( int x : { Q1teamOne, Q2teamOne, Q3teamOne, Q4teamOne } ) std::cout << x << ' ';
std::cout << std::endl;
what about:
teamOneScore[ 0 ] = Q1teamOne;
teamOneScore[ 1 ] = Q2teamOne;
teamOneScore[ 2 ] = Q3teamOne;
teamOneScore[ 3 ] = Q4teamOne;
teamTwoScore[ 0 ] = Q1teamTwo;
teamTwoScore[ 1 ] = Q2teamTwo;
teamTwoScore[ 2 ] = Q3teamTwo;
teamTwoScore[ 3 ] = Q4teamTwo;
But consider:
the arrays teamOneScore and teamTwoScore are arrays of double and your scores are int, so:
change the type of the arrays to be ints or
cast the assignment as: teamOneScore[ 0 ] = static_cast< double >( Q1teamOne );
Also, just for your information, this comparison is not correct:
else if (Q4TeamOneTotal = Q4TeamTwoTotal)
It should be:
else if (Q4TeamOneTotal == Q4TeamTwoTotal)
As a final note, you can use the arrays to store the scores from the cin and avoid the use of the Q1teamOne, ... vars.