Matrix Class input operator overload - c++

Hello I have an assignment to implement a Matrix class using pointers.
class matrixType{
private:
int **matrix;
int numRows;
int numColumns;
public:
istream& operator >>(istream& ins, const matrixType& source);
}
I'm having trouble with the input operator for this! For some reason this operator overload is not making sense to me, but I also have a function that also allows for user input which isn't an overload.
void matrixType::setMatrix(){
int i,k,value;
cout << "Be prepared to enter values to be inserted into your matrix: " << endl;
for(i=0; i<rowSize; i++){
for(k=0; k<columnSize; ++k){
cout << "Value [" << i << "][" << k << "]: ";
cin >> value;
matrix[i][k]=value;
}
}
cout << endl;
}
Can someone help me on the input operator?
Thank you!

The input operator overloading function allows you to use the object of a class or struct directly into function like cin. This way you can directly ask for all inputs by writing a single statement that inputs the object and it will input all the values itself.
The program should be like
class matrixType{
private:
int **matrix;
int numRows;
int numColumns;
public:
istream& operator>>(istream& input, const matrixType& source)
{
for(int i=0;i<numRows;i++)
for(int j=0;j<numColumns;j++)
input>>source.matrix[i][j];
return input;
}
}
Now You can input the values directly using cin like this
matrixType A;
cin>>A;

Related

C++ Program with clasess

I'm trying to make a program and while I'm making it I'm learning classes, inheritance and things I'll need. I'll give you the condition of the program and the code to where I got to.
The 2nd class I made it inherit the 1st, but I can't get the console to return the student's grade. Тhe condition they gave me confuses me and I can't figure out how they want to calculate the student's grade? Thanks in advance for your time and kindness :)
I. Define a student class CStudent storing name information,
student's faculty number and major to provide:
Create objects using a copy constructor
Creation of objects by explicit constructor (with parameters)
Using an implicit constructor
Assignment operator =
Comparison operator ==
Comparison operator < (by faculty number)
To read student data from stream input - operator>>
To output the student data to stream output - operator<<
Establish the member variables (mutators)
Reading the member variables (accessors)
II. Define a student booklet class CStudBook that inherits
CStudent with a member data container of the student's grades. To implement
a constructor with a filename parameter from which to initialize
container and the following methods:
Create an object using another object (copy constructor)
Creating an object using explicit parameters
Creating an object by default constructor
Calculate and return the student's grade point average
operator>>
operator<<
Print
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <algorithm>
using namespace std;
class CStudent {
public:
// Default constructor
CStudent() = default;
// Explicit constructor
CStudent(string name, int facnum, string specialty) {
this->name = name;
this->facnum = facnum;
this->specialty = specialty;
}
// Copy constructor
CStudent(const CStudent& obj) {
this->name = obj.name;
this->facnum = obj.facnum;
this->specialty = obj.specialty;
}
// Method, that prints the contents of the object
void PrintStudent() const {
cout << "Name: " << name << endl;
cout << "Fac. num: " << facnum << endl;
cout << "Specialty: " << specialty << endl;
}
friend std::ostream& operator <<(std::ostream& out, const CStudent& obj) // output operator
{
out << "Name:" << obj.name << "-> FacNumber: " << obj.facnum << std::endl;
}
bool operator <(const CStudent& obj) // operator for comparison of two objects
{
return name < obj.name;
return facnum < obj.facnum;
}
// operator login should be added here
private:
string name;
int facnum;
string specialty;
};
class CStudBook : public CStudent {
private:
int grade;
};
// Function, that gets student data from the console
// and creates an instance of the CStudent class using this data
CStudent CreateFromConsole() {
cout << "Enter name: ";
string name;
cin >> name;
cout << "Enter fac. num: ";
int facnum;
cin >> facnum;
cout << "Enter specialty: ";
string specialty;
cin >> specialty;
cout << "Enter student grade: ";
int grade;
cin >> grade;
cout << endl;
return CStudent(name, facnum, specialty); // returns an instance of the class
}
int main() {
vector<CStudent> students; // stack-like container
cout << "Enter total number of students: ";
int count;
cin >> count;
cout << "Enter details of students" << endl << endl;
for (int i = 0; i < count; i++) {
// Create an instance of the class
CStudent student = CreateFromConsole();
// Push a copy of the object into the container
students.push_back(student);
}
cout << endl;
cout << "Details" << endl << endl;
for (int i = 0; i < students.size(); i++) {
students[i].PrintStudent();
cout << endl;
}
fflush(stdin); // Reset input console
getchar(); // Pause
return 0;
}
I think grade is private members of class CStudBook so you can't call it from class CStudent.
If you want to access it my suggested keyword for you to find is protected members

C++ friend operator overloading cin>>

I am replacing a Read in function with a friend operator. I am having trouble referencing the friend operator in a void function. I am receiving and error "No member named 'Read' in Date" in the void GetDates function. Does anyone know how to fix this? Thank you!
Question 2:
I am now using cout<< operator but I am receiving errors for my variables: "'mn' is a private member of 'Date'"
class Date {
private:
int mn; //month component of a date
int dy; //day component of a date
int yr; //year comonent of a date
public:
//constructors
Date() : mn(0), dy(0), yr(0)
{}
Date(int m, int d, int y) : mn(m), dy(d), yr(y)
{}
//input/output functions
friend istream& operator>>(istream& Read, Date& d); //overload friend Read
friend ostream& operator<<(istream& write, Date& d); //overload friend write
void GetDates();
void Sort();
};
//Date class member functions
istream& operator >>(istream& Read, Date& d) //**NEED TO REPLACE with overload vs as friends to Date function**
{
char skip_char;
Read >> d.mn >> skip_char >> d.dy >> skip_char >> d.yr;
return Read;
}
void GetDates(Date l[], int &n) //reads list l, and returns count in n
{
cout << "How many date values are to be processed (1 - 100)? ";
cin >> n;
while ((n < 0) || (n > 100)) {
cout << "Invalid value; enter number between 0 and 100: ";
cin >> n;
}
for (int i = 0; i < n; i++) {
cout << "Enter a date (mm/dd/yyyy): ";
l[i].Read(); //ERROR HERE
}
}
ostream& operator <<(ostream& write, Date& d) //friend write
{
if (d.mn < 10)
cout << '0';
cout << d.mn << '/';
if (d.dy < 10)
cout << '0';
cout << d.dy << '/';
if (d.yr < 1000)
cout << '0';
if (d.yr < 100)
cout << '0';
if (d.yr < 10)
cout << '0';
cout << d.yr;
return write;
}
Read is the name of the stream that you are extracting from. An example of a stream that you can read from is cin. You need to replace this line:
l[i].Read(); //ERROR HERE
with
cin >> l[i];
Inside operator>> the cin object is now called Read.
The issue with your operator<< is that it needs to be declared as a friend, the same way you've done with operator>>.
Also, you are writing to cout instead of writing to write. This will not work, as soon as you try to writing to any other stream.

How can I use vector or algorithm for finding maximum amount in this code?

I wrote following code for finding maximum score:
#include "stdafx.h"
#include <iostream>
#include<vector>
#include <string>
#include <algorithm>
constexpr int MAX_STUDENTS = 3;
using namespace std;
class student{
public:
void vrod();
void dis();
int stno;
int score
int i;
string name;
};
void student::vrod(){
cout << "name=";
cin >> name;
cout << "stno=";
cin >> stno;
cout << "score=";
cin >> score;
}
void student::dis(){
cout << "name=" << name << "\n" << "stno=" << stno << "\n" << "score=" << score<< "\n";
cin.get();
}
int main(){
int l;
vector<student> my_vector;
for(int i = 0; i < n; i++)
{
student new_student;
cout << "Number: ";
cin >> new_student.stno;
cout << "Score: ";
cin >> new_student.score;
cout << "Name: ";
cin >> new_student.name;
my_vector.push_back(new_student);
}
l=0;
for(int i = 0; i < MAX_STUDENTS; ++i)
{
if (my_vector[i].score>l) {
l=my_vector[i].score;
}
}
cout << "max=" << l;
cin.get();
cin.get();
}
I used common ways to find maximum amount, but how can I use vector? how about algorithm? I found that there is a function which is max in algorithm, but it needs two argument and I could not use that for this code. Thanks for your tips beforehand.
You can use std::max_element and a lambda expression for the comparator:
auto l = std::max_element(my_vector.cbegin(), my_vector.cend(),
[](const student& s1, const student& s2) {
return s1.score < s2.score;
});
l is a const iterator, to output maximum score you need to check if it did return anything and output the score
if(l != my_vector.cend()){
cout << "max=" << l->score;
}
Also a few tips:
Don't do
#define n 3
This is C++, and giving meaningful variable names is a good practice you can use
constexpr int MAX_STUDENTS = 3;
You aren't using student::vrod() and student:dis() methods anywhere
UPDATE (OP request):
Lambda expressions is a more convenient way to write functions for various uses. Lambda in this case
[](const student& s1, const student& s2) {
return s1.score < s2.score;
}
is a more convenient way to write a comparator function, it can also be implemented with a functor
struct compare_students {
bool operator() (const student& s1, const student& s2) const {
return s1.score < s2.score;
}
};
auto l = std::max_element(my_vector.cbegin(), my_vector.cend(), compare_students());
For more information please consider searching for C++ lambda tutorials and examples.
int max_score = std::max_element(
my_vector.begin(),
my_vector.end(),
[] (student const& lhs, student const& rhs){
return lhs.score < rhs.score;
}
)->score;
is one way. Note the use of the lambda function acting as the comparator.
Pre C++11, you'd use a function object to model the comparator.

Operator Overloading C++; too many parameters for << operation

I have some code below that will take some names and ages and do some stuff with them. Eventually it will print them out. I need to change my print() function with a global operator<<. I saw on a different forum that <<operator takes two parameters, but when I try it I get a "too many parameters for << operation error. Is there something I am doing wrong? I am newer to C++ and I really do not get the point of operator overloading.
#include <iostream>;
#include <string>;
#include <vector>;
#include <string.h>;
#include <fstream>;
#include <algorithm>;
using namespace::std;
class Name_Pairs{
vector<string> names;
vector<double> ages;
public:
void read_Names(/*string file*/){
ifstream stream;
string name;
//Open new file
stream.open("names.txt");
//Read file
while(getline(stream, name)){
//Push
names.push_back(name);
}
//Close
stream.close();
}
void read_Ages(){
double age;
//Prompt user for each age
for(int x = 0; x < names.size(); x++)
{
cout << "How old is " + names[x] + "? ";
cin >> age;
cout<<endl;
//Push
ages.push_back(age);
}
}
bool sortNames(){
int size = names.size();
string tName;
//Somethine went wrong
if(size < 1) return false;
//Temp
vector<string> temp = names;
vector<double> tempA = ages;
//Sort Names
sort(names.begin(), names.end());
//High on performance, but ok for small amounts of data
for (int x = 0; x < size; x++){
tName = names[x];
for (int y = 0; y < size; y++){
//If the names are the same, then swap
if (temp[y] == names[x]){
ages[x] = tempA[y];
}
}
}
}
void print(){
for(int x = 0; x < names.size(); x++){
cout << names[x] << " " << ages[x] << endl;
}
}
ostream& operator<<(ostream& out, int x){
return out << names[x] << " " << ages[x] <<endl;
}
};
You are overloading << operator as a member function, therefore, the first parameter is implicitly the calling object.
You should either overload it as friend function or as a free function. For example:
overloading as friend function.
friend ostream& operator<<(ostream& out, int x){
out << names[x] << " " << ages[x] <<endl;
return out;
}
However, the canonical way is to overload it as free function. You can find very good information from this post: C++ operator overloading
declare operator overloading function as friend.
friend ostream& operator<<(ostream& out, int x)
{
out << names[x] << " " << ages[x] <<endl;
return out;
}

C++ Array outputting address?

I posted earlier for the first time and was able to almost complete this assignment. The program isn't giving an error, but I'm getting undesired results. The output appears to be outputting the array address instead of the data I input. Or at least I think it is based on my very very limited knowledge. Can anyone help guide me in how to fix this? I've been working on this all day and at this hour, I think I'm ready to throw in the towel. Any advice is greatly appreciated, thanks!
// Amanda
// SoccerPlayer.cpp : main project file.
// October 6, 2012
/* a. Design a SoccerPlayer class that includes three integer fields: a player's jersey number,
number of goals, and number of assists. Overload extraction and insertion operators for the class.
b. Include an operation>() function for the class. One SoccerPlayer is considered greater
than another if the sum of goals plus assists is greater.
c. Create an array of 11 SoccerPlayers, then use the > operator to find the player who has the
greatest goals plus assists.*/
#include "stdafx.h"
#include<conio.h>
#include<iostream>
#include<string>
using namespace std;
class SoccerPlayer
{
friend std::ostream& operator<<(std::ostream&, const SoccerPlayer&);
friend istream& operator>>(istream&, SoccerPlayer&);
private:
int jerseyNum;
int numGoals;
int numAssists;
public:
SoccerPlayer(int, int, int);
int score;
int operator>(SoccerPlayer&);
void DisplayStar();
};
SoccerPlayer::SoccerPlayer(int jersey = 0, int goal = 0, int assist = 0)
{
jerseyNum = jersey;
numGoals = goal;
numAssists = assist;
}
void SoccerPlayer::DisplayStar()
{
cout<<"Player Number: "<< jerseyNum <<endl;
cout<<"Goals Scored: "<< numGoals <<endl;
cout<<"Assists Made: "<< numAssists <<endl;
}
std::ostream& operator<<(std::ostream& player, const SoccerPlayer& aPlayer)
{
player << "Jersey #" << aPlayer.jerseyNum <<
" Number of Goals " << aPlayer.numGoals <<
" Number of Assists " << aPlayer.numAssists;
return player;
}
std::istream& operator>>(std::istream& inPlayer, SoccerPlayer& aPlayer)
{
cout << "Please enter the jersey number: ";
inPlayer >> aPlayer.jerseyNum;
cout << "Please enter the number of goals: ";
inPlayer >> aPlayer.numGoals;
cout << "Please enter the number of assists: ";
inPlayer >> aPlayer.numAssists;
aPlayer.score=(aPlayer.numGoals) + (aPlayer.numAssists);
return inPlayer;
}
int SoccerPlayer::operator>(SoccerPlayer& aPlayer)
{
int total = 0;
if (score > aPlayer.score)
total = 1;
return total;
}
int main()
{
const int sz = 11;
int x;
SoccerPlayer aPlayer[sz];
for(x = 0; x < sz; ++x)
cin >> aPlayer[x];
{
double max = aPlayer[x].score;
for(int i = 1; i<sz; ++i)
{
if(aPlayer[i] > aPlayer[x])
{
max=aPlayer[i].score;
}
}
cout << max << endl;
cout << aPlayer[x];
}
_getch();
return 0;
}
It looks as if you intended a loop here, but it's malformed:
for(x = 0; x < sz; ++x)
cin >> aPlayer[x];
{
double max = aPlayer[x].score;
for(int i = 1; i<sz; ++i)
{
if(aPlayer[i] > aPlayer[x])
{
max=aPlayer[i].score;
}
}
cout << max << endl;
cout << aPlayer[x];
}
You meant (I think) that double max ... should be inside the loop, but the cin >> ... line comes after the for statement, outside the braces. So the iteration applies only to the cin >> ... statement; once it's done, control proceeds to double max = aPlayer[x].score;, but x (left over from for(...)) is equal to sz, so aPlayer[x] is outside the array, in no-man's-land.
Put the cin >> ... inside the brackets.
The problem is that you only print the element aPlayer[x]. But notice that your first for loop terminates when x = 11. Well, that's one past the end of the array, so really, you're outputting junk.
I just tried it out with aPlayer[0] instead and got expected results.
This is what I ended up with. Thanks everyone for the help!
// Amanda
// SoccerPlayer.cpp : main project file.
// October 6, 2012
/* a. Design a SoccerPlayer class that includes three integer fields: a player's jersey number,
number of goals, and number of assists. Overload extraction and insertion operators for the class.
b. Include an operation>() function for the class. One SoccerPlayer is considered greater
than another if the sum of goals plus assists is greater.
c. Create an array of 11 SoccerPlayers, then use the > operator to find the player who has the
greatest goals plus assists.*/
#include "stdafx.h"
#include<conio.h>
#include<iostream>
#include<string>
using namespace std;
//soccer player class - see above description
class SoccerPlayer
{
friend std::ostream& operator<<(std::ostream&, const SoccerPlayer&);
friend istream& operator>>(istream&, SoccerPlayer&);
private:
int jerseyNum;
int numGoals;
int numAssists;
public:
SoccerPlayer(int, int, int);
int score;
int operator>(SoccerPlayer&);
void DisplayStar();
};
//soccerplayer constructor
SoccerPlayer::SoccerPlayer(int jersey = 0, int goal = 0, int assist = 0)
{
jerseyNum = jersey;
numGoals = goal;
numAssists = assist;
}
//to display star player
void SoccerPlayer::DisplayStar()
{
cout<<"Jersey #: "<< jerseyNum <<endl;
cout<<"Goals Scored: "<< numGoals <<endl;
cout<<"Assists Made: "<< numAssists <<endl;
}
//overload operator out
std::ostream& operator<<(std::ostream& player, const SoccerPlayer& aPlayer)
{
player << "Jersey #" << aPlayer.jerseyNum <<
" Number of Goals " << aPlayer.numGoals <<
" Number of Assists " << aPlayer.numAssists;
return player;
}
//overload operator in
std::istream& operator>>(std::istream& inPlayer, SoccerPlayer& aPlayer)
{
cout << "Please enter the jersey number: ";
inPlayer >> aPlayer.jerseyNum;
cout << "Please enter the number of goals: ";
inPlayer >> aPlayer.numGoals;
cout << "Please enter the number of assists: ";
inPlayer >> aPlayer.numAssists;
aPlayer.score=(aPlayer.numGoals) + (aPlayer.numAssists);
return inPlayer;
}
//overload operator greater than
int SoccerPlayer::operator>(SoccerPlayer& aPlayer)
{
int total = 0;
if (score > aPlayer.score)
total = 1;
return total;
}
//main declaration
int main()
{
//11 players
const int sz = 11;
int x;
SoccerPlayer aPlayer[sz];
double max = 0;
//to display star
SoccerPlayer Star;
//allow user to input players, show what they input
for(x = 0; x < sz; ++x)
{
cin >> aPlayer[x];
cout << aPlayer[x] << endl << endl;
for(int i=1; i<sz; i++)
{
Star=aPlayer[0];
if(aPlayer[i] > aPlayer[i+1])
Star=aPlayer[i];
}
}
//show star player
cout << "The Star Player: "<< endl;
Star.DisplayStar();
_getch();
return 0;
}