This is a basic program to get two 5-digit numbers as string and use addition on the 2 numbers utilising operator overloading on '+' .
#include <iostream>
#include <limits>
#include <cstdlib>
#include <cstring>
#include <sstream>
using namespace std;
class IntStr
{
int InputNum;
public:
//IntStr();
IntStr::IntStr(int num);
IntStr operator+ (const IntStr &);
//~IntStr();
void Display();
};
IntStr::IntStr(int num)
{
InputNum = num;
}
void IntStr::Display()
{
cout << "Number is (via Display) : " << InputNum <<endl;
}
IntStr IntStr::operator+ (const IntStr & second) {
int add_result = InputNum + second.InputNum;
return IntStr(add_result);
}
int main()
{
string str;
bool option = true;
bool option2 = true;
while (option)
{
cout << "Enter the number : " ;
if (!getline(cin, str))
{
cerr << "Something went seriously wrong...\n";
}
istringstream iss(str);
int i;
iss >> i; // Extract an integer value from the stream that wraps str
if (!iss)
{
// Extraction failed (or a more serious problem like EOF reached)
cerr << "Enter a number dammit!\n";
}
else if (i < 10000 || i > 99999)
{
cerr << "Out of range!\n";
}
else
{
// Process i
//cout << "Stream is: " << iss << endl; //For debugging purposesc only
cout << "Number is : " << i << endl;
option = false;
IntStr obj1 = IntStr(i);
obj1.Display();
}
}//while
while (option2)
{
cout << "Enter the second number : " ;
if (!getline(cin, str))
{
cerr << "Something went seriously wrong...\n";
}
istringstream iss(str);
int i;
iss >> i; // Extract an integer value from the stream that wraps str
if (!iss) //------------------------------------------> (i)
{
// Extraction failed (or a more serious problem like EOF reached)
cerr << "Enter a number dammit!\n";
}
else if (i < 10000 || i > 99999)
{
cerr << "Out of range!\n";
}
else
{
// Process i
//cout << "Stream is: " << iss << endl; //For debugging purposes only
cout << "Number is : " << i << endl;
option2 = false;
IntStr obj2 = IntStr(i);
obj2.Display();
//obj1->Display();
}
}//while
//IntStr Result = obj1 + obj2; // --------------------> (ii)
//Result.Display();
cin.get();
}
Need clarification on the points (i) & (ii) in the above code ...
(1) What does (i) actually do ?
(2) (ii) -> Does not compile.. as the error "obj1 not declared (first use this function)" comes up. Is this because obj1 & obj2 are declared only inside the while loops? How do I access them globally?