I'm just a new to C++ And i'm at the beginning...Just want some help...would be appreciate it if somebody can explain where am I wrong with this:
First of all my Time.h code:
#ifndef TIME_H
#define TIME_H
#include<iostream>
using namespace std;
class time {
friend istream &operator>> (istream &, time);
private:
int hour;
int minute;
int second;
public:
time(int = 0, int = 0, int = 0);
void settime(int, int, int);
void sethour(int);
void setminute(int);
void setsecond(int);
};
#endif
And now, Time.cpp:
#include<iostream>
#include"Time.h"
using namespace std;
using std::cout;
using std::cin;
time::time(int h, int m, int s)
{
settime(h, m, s);
}
void time::settime(int hr, int min, int sec)
{
sethour(hr);
setminute(min);
setsecond(sec);
}
void time::sethour(int h)
{
hour = (h >= 0 && h < 24) ? h : 0;
}
void time::setminute(int m)
{
minute = (m >= 0 && m < 60) ? m : 0;
}
void time::setsecond(int s)
{
second = (s >= 0 && s < 60) ? s : 0;
}
istream &operator>> (istream &in, time m)
{
in >> m.sethour >> m.setminute >> m.setsecond;
}
And finally source.cpp:
#include<iostream>
#include"D:\headers\Time.h"
using namespace std;
void main()
{
time t;
cin >> t;
system("pause");
}
But when I compile it, it gives me an error:
1.Error C3867 'time::sethour': non-standard syntax; use '&' to create a pointer to member Project33 D:\headers\Time.cpp
2.Error C2679 binary '>>': no operator found which takes a right-hand operand of type 'overloaded-function' (or there is no acceptable conversion) Project33 D:\headers\Time.cpp
Can anybody help me out???
sethour is a member function not a member variable. You need to use a variable.
You can use:
istream &operator>> (istream &in, time m)
{
return (in >> m.hour >> m.minute >> m.second);
}
However, that won't do the calling function any good because you are changing a copy. You need to pass m by reference.
istream &operator>> (istream &in, time& m)
{
return (in >> m.hour >> m.minute >> m.second);
}
Make sure to change the declaration accordingly.
Had the function not been a friend of the class, you could use:
istream &operator>> (istream &in, time& m)
{
// Read the data.
int hour;
int minute;
int second;
in >> m.hour >> m.minute >> m.second;
// Set the member values using function calls.
m.sethour(hour);
m.setminute(minute);
m.setsecond(second);
return in;
}
You're reading into functions here:
in >> m.sethour >> m.setminute >> m.setsecond;
^ ^ ^
That's a simple typo. The bigger problem is that you take the time by value, which prevents any modifications from it to propagating; you probably wanted to take a reference there.
Related
I am experimenting with reading input from command line and successfully store them in objects attributes.
Example of input (./(nameOfExecutable) < (sourceText) in the command line)
20 5
1 5
28 5
2 5
20 5
4 5
22 5
88 3
27 5
34 5
I want to read and store them into object attributes.
experimentClass.h
#ifndef EXPERIMENTCLASS_H
#define EXPERIMENTCLASS_H
#pragma once
class experimentClass
{
public:
experimentClass(int x, int y);
~experimentClass();
private:
int age;
int favoriteNumber;
};
#endif
experimentClass.cpp
#include "experimentClass.h"
experimentClass::experimentClass(int x, int y)
{
age = x;
favoriteNumber = y;
}
experimentClass::~experimentClass()
{
}
main.cpp
#include <iostream>
#include "experimentClass.h"
using namespace std;
int main(){
int age;
int favoriteNumber;
std::cin >> age;
std::cin >> favoriteNumber;
experimentClass a(age, favoriteNumber);
}
In this case, I am able to store 20 into a's age, 5 into a's favoriteNumber.
However, I want to do this process until it hits the end of input.
So, in this case, I want to create 10 objects with given input, using iteration, and store these object into an array or something.
How can I read them properly so that I can achieve this?
Simply take the logic you already have and put it inside a loop, eg:
#include <iostream>
#include <vector>
#include "experimentClass.h"
using namespace std;
int main() {
int age;
int favoriteNumber;
vector<experimentClass> vec;
while (cin >> age >> favoriteNumber) {
experimentClass a(age, favoriteNumber);
vec.push_back(a);
}
// use vec as needed...
}
Then you can take this a step further by implementing an operator>> for your class, eg:
#ifndef EXPERIMENTCLASS_H
#define EXPERIMENTCLASS_H
#include <istream>
#pragma once
class experimentClass
{
public:
experimentClass(int x = 0, int y = 0);
friend std::istream& operator>>(std::istream &is, experimentClass &cls);
private:
int age;
int favoriteNumber;
};
std::istream& operator>>(std::istream &is, experimentClass &cls);
#endif
#include "experimentClass.h"
experimentClass::experimentClass(int x, int y)
{
age = x;
favoriteNumber = y;
}
std::istream& operator>>(std::istream &is, experimentClass &cls)
{
return is >> cls.age >> cls.favoriteNumber;
}
#include <iostream>
#include <vector>
#include "experimentClass.h"
using namespace std;
int main() {
experimentClass a;
vector<experimentClass> vec;
while (cin >> a) {
vec.push_back(a);
}
// use vec as needed...
}
You could model the input line with a struct:
struct Record
{
unsigned int m_age;
int m_favorite_number;
};
Then overload the operator>>:
struct Record
{
unsigned int m_age;
int m_favorite_number;
friend std::istream& operator>>(std::istream& input, Record& r);
};
std::istream& operator>>(std::istream& input, Record& r)
{
input >> r.m_age;
input >> r.m_favorite_number;
return input;
}
You could read in the data into a database by using:
std::vector<Record> database;
Record r;
while (std::cin >> r)
{
database.push_back(r);
}
In the above call, you could replace std::cin with a file stream.
You could print or display a record from the database:
std::cout << database[3].m_age << " " << database[3].m_favorite_number << "\n";
Although IMHO, you should overload operator<< to print the record in a default format.
Since you are using nameOfExecutable.exe < source.txt, you can use cin.eof to check if the end of file is reached:
while(true){
int a, b;
std::cin >> a;
if(std::cin.eof()){
break;
}
std::cin >> b;
//Create Class
}
Need help figuring out what's the issue with the following source code. I've got a single class to count a number of characters and display each one of them into the console screen.
But unfortunately i kept getting this error message when i tried compiling
error C2678: binary '>>' : no operator found which takes a left-hand operand of type 'std::istream' (or there is no acceptable conversion)
The following are the source files:
CharacterCounter.h
#include <iostream>
class CharacterCounter {
public:
int fTotalNumberOfCharacters;
int fCharacterCounts[256]; // hold all 256 byte values
public:
CharacterCounter();
void count(unsigned char aCharacter);
friend std::ostream& operator<<(std::ostream& aOStream, CharacterCounter& aCharacterCounter);
};
}
CharacterCounter.cpp
#include "CharacterCounter.h"
#include <iostream>
/// Constructor
CharacterCounter::CharacterCounter() {
fTotalNumberOfCharacters = 0;
for (int i=0; i < 256; i++) {
fCharacterCounts[i] = i;
}
}
/// Counts the corresponding data member
void CharacterCounter::count(unsigned char aCharacter) {
fTotalNumberOfCharacters++;
fCharacterCounts[aCharacter]++;
}
/// Output stream displays characters greater than 0
std::ostream& operator<<(std::ostream& aOStream, const CharacterCounter& aCharacterCounter) {
for (int i=0; i < 256; i++) {
if (aCharacterCounter.fCharacterCounts[i] > 0) {
int character = aCharacterCounter.fCharacterCounts[i];
aOStream << (unsigned char)i << ":\t" << character << "\n";
}
}
return aOStream;
}
Main.cpp
#include <iostream>
#include <string>
#include "CharacterCounter.h"
using namespace std;
int main() {
CharacterCounter counter;
unsigned char character;
while (cin >> counter) { **Compilation error focuses here**
counter.count(character);
}
cout << counter;
system("pause");
return 0;
};
You need to overload operator >> for your CharacterCounter, because of cin >> counter, declare it:
class CharacterCounter {
public:
//...
friend std::istream& operator>>(std::istream& input, CharacterCounter& aCharacterCounter);
//...
And then declare function overload:
std::istream &operator>>( std::istream &input, CharacterCounter& aCharacterCounter )
{
input >> aCharacterCounter. fTotalNumberOfCharacters;
// Or input something else or more
return input;
}
.cpp
//
// calculator.cpp
//
#include "Fraction.h"
#include<iostream>
#include<stdexcept>
using namespace std;
int main()
{
Fraction x,y; //ERROR IS RIGHT HERE. It says "No matching constructor for initialization of 'Fraction'
char op;
try
{
cin >> x;
cin >> op;
while ( cin && ( op == '+' || op == '-' ) )
{
cin >> y;
if ( op == '+' )
x = x + y;
else
x = x - y;
cin >> op;
}
cout << x << endl;
}
catch ( invalid_argument& e )
{
cout << "Error: " << e.what() << endl;
}
}
.h
#ifndef Fraction_Calculator_Fraction_h
#define Fraction_Calculator_Fraction_h
#include<iostream>
#include<cstdlib>
//Fraction class definition
class Fraction
{
public:
Fraction (int a, int b);
int fraction(int a, int b);
void set(int, int);
int get_numerator(void);
int get_denomenator(void);
int find_gcd (int n1, int n2);
void reduce_fraction(int nump, int denomp);
Fraction& operator+(const Fraction& n);
Fraction& operator-(const Fraction& n);
friend std::ostream& operator<<(std::ostream &os, const Fraction& n);
friend std::istream& operator>>(std::istream &is, Fraction& n);
Fraction& operator= (const Fraction& n);
int denom;
int numera;
private:
int numerator;
int denomenator;
int denomp;
int nump;
};
#endif
It says "No matching constructor for initialization of 'Fraction' on the first line of the cpp file
I don't understand what it means.
The problem is that your Fraction constructor takes 2 arguments.
Fraction (int a, int b);
and you are invoking it with none
Fraction x,y; //ERROR IS RIGHT HERE. It says "No matching constructor for initialization of 'Fraction'
You should either invoke x and y with the 2 int parameters or define another constructor that takes no arguments.
Provide default constructor like
Fraction()
{
numerator=0;
denomenator0;
denomp0;
nump=0;
}
I need to rewrite the << operator so that it can cout values for hour (int) and temperature (double).
I think I've included all necessary sections. Thanks in advance.
struct Reading {
int hour;
double temperature;
Reading(int h, double t): hour(h), temperature(t) { }
bool operator<(const Reading &r) const;
};
========
ostream& operator<<(ostream& ost, const Reading &r)
{
// unsure what to enter here
return ost;
}
========
vector<Reading> get_temps()
{
// stub version
cout << "Please enter name of input file name: ";
string name;
cin >> name;
ifstream ist(name.c_str());
if(!ist) error("can't open input file ", name);
vector<Reading> temps;
int hour;
double temperature;
while (ist >> hour >> temperature){
if (hour <0 || 23 <hour) error("hour out of range");
temps.push_back( Reading(hour,temperature));
}
}
For example like this:
bool operator <(Reading const& left, Reading const& right)
{
return left.temperature < right.temperature;
}
And it should be a global function (or in the same namespace as Reading), not a member or Reading, it should be declared as a friend if you going to have any protected or private members. This could be done like so:
struct Reading {
int hour;
double temperature;
Reading(int h, double t): hour(h), temperature(t) { }
friend bool operator <(Reading const& left, Reading const& right);
};
You probably want something like
ost << r.hour << ' ' << r.temperature;
This is pretty simple stuff though, and if it doesn't make sense you should really talk to someone or get a book.
And if it still doesn't make sense or you can't be bothered, consider choosing another hobby/career.
IIRC, you can do it one of two ways ...
// overload operator<
bool operator< ( const Reading & lhs, const Reading & rhs )
{
return lhs.temperature < rhs.temperature;
}
or, you can add the operator to your struct ...
struct Reading {
int hour;
double temperature;
Reading ( int h, double t ) : hour ( h ), temperature ( t ) { }
bool operator< ( const Reading & other ) { return temperature < other.temperature; }
}
Use ost parameter like std::cout in operator<<.
r.hour()
r.temperature()
You've declared hour and temperature as member fields of Reading, not member methods. Thus they are simply r.hour and r.temperature (no ()).
As hour and temperature are variables rather than functions, just remove the trailing () from the operator<< functions.
You can overload an operator like this in c++.
struct Reading {
int hour;
double temperature;
Reading(int h, double t): hour(h), temperature(t) { }
bool operator<(struct Reading &other) {
//do your comparisons between this and other and return a value
}
}
I need to rewrite the << operator so that it can cout values for hour (int) and temperature (double).
I think I've included all necessary sections. Thanks in advance.
struct Reading {
int hour;
double temperature;
Reading(int h, double t): hour(h), temperature(t) { }
bool operator<(const Reading &r) const;
};
========
ostream& operator<<(ostream& ost, const Reading &r)
{
// unsure what to enter here
return ost;
}
========
vector<Reading> get_temps()
{
// stub version
cout << "Please enter name of input file name: ";
string name;
cin >> name;
ifstream ist(name.c_str());
if(!ist) error("can't open input file ", name);
vector<Reading> temps;
int hour;
double temperature;
while (ist >> hour >> temperature){
if (hour <0 || 23 <hour) error("hour out of range");
temps.push_back( Reading(hour,temperature));
}
}
For example like this:
bool operator <(Reading const& left, Reading const& right)
{
return left.temperature < right.temperature;
}
And it should be a global function (or in the same namespace as Reading), not a member or Reading, it should be declared as a friend if you going to have any protected or private members. This could be done like so:
struct Reading {
int hour;
double temperature;
Reading(int h, double t): hour(h), temperature(t) { }
friend bool operator <(Reading const& left, Reading const& right);
};
You probably want something like
ost << r.hour << ' ' << r.temperature;
This is pretty simple stuff though, and if it doesn't make sense you should really talk to someone or get a book.
And if it still doesn't make sense or you can't be bothered, consider choosing another hobby/career.
IIRC, you can do it one of two ways ...
// overload operator<
bool operator< ( const Reading & lhs, const Reading & rhs )
{
return lhs.temperature < rhs.temperature;
}
or, you can add the operator to your struct ...
struct Reading {
int hour;
double temperature;
Reading ( int h, double t ) : hour ( h ), temperature ( t ) { }
bool operator< ( const Reading & other ) { return temperature < other.temperature; }
}
Use ost parameter like std::cout in operator<<.
r.hour()
r.temperature()
You've declared hour and temperature as member fields of Reading, not member methods. Thus they are simply r.hour and r.temperature (no ()).
As hour and temperature are variables rather than functions, just remove the trailing () from the operator<< functions.
You can overload an operator like this in c++.
struct Reading {
int hour;
double temperature;
Reading(int h, double t): hour(h), temperature(t) { }
bool operator<(struct Reading &other) {
//do your comparisons between this and other and return a value
}
}