Here we go, I am working on some code to store an IP address in an object. I have overloaded operators >>, <<, and == and they are working fine with 1 problem. I am supposed to be able to cin >> ip1 >> ip2 >> ip3; but after I input the first IP I get a bus error. If I seperate the cin's(cin >> ip1; cin >> ip2; cin >> ip3;) it works fine.heres the code:
test.cpp
#include <iostream>
//#include "Time.h" //not using Time class at this moment
#include "IPAddress.h"
using namespace std;
int main()
{
IPAddress ip1, ip2, ip3;
cout << ip1 << ip2 << endl;
cin >> ip1 >> ip2 >> ip3;
//cin >> ip2;
//cin >> ip3;
cout << ip1 << endl;
if(ip1 == ip2) cout << "Same" << endl;
if(ip1 == ip3) cout << "Same" << endl;
return 0;
}
IPAddress.h
#include <iostream>
using namespace std;
class IPAddress
{
friend ostream& operator<< (ostream&, const IPAddress&);
friend istream& operator>> (istream&, IPAddress&);
public:
IPAddress();
int p1, p2, p3, p4;
bool operator==(const IPAddress &) const;
};
IPAddress.cpp
#include <iostream>
#include "IPAddress.h"
#include <string.h>
using namespace std;
IPAddress::IPAddress()
{
p1 = 0;
p2 = 0;
p3 = 0;
p4 = 0;
}
bool IPAddress::operator==(const IPAddress &t2) const
{
if((*this).p1 == t2.p1 && (*this).p2 == t2.p2 && (*this).p3 == t2.p3 && (*this).p4 == t2.p4) return true;
else return false;
}
ostream& operator<< (ostream &out, const IPAddress &r)
{
out << r.p1 << "." << r.p2 << "." << r.p3 << "." << r.p4 << endl;
return out;
}
istream& operator>> (istream &in, IPAddress &r)
{
char mystring[16];
char *str1, *str2, *str3, *str4;
int ptr1, ptr2, ptr3;
in >> mystring;
str1 = strtok(mystring, "."); //tokenize IP string to seperate strings
str2 = strtok(NULL, ".");
str3 = strtok(NULL, ".");
str4 = strtok(NULL, "\0");
r.p1 = atoi(str1); //store IP in object
r.p2 = atoi(str2);
r.p3 = atoi(str3);
r.p4 = atoi(str4);
}
Yeah I'm using c style strings in c++ code get over it :)
Normally I wouldn't bother about something that could be fixed by coding seperate lines instead of putting it all in one, but the instructor specified to use this to test the code. Thanks for the help.