Question

Using the following code perform ALL of the tasks below in C++: ------------------------------------------------------------------------------------------------------------------------------------------- Implementation: Overload input...

Using the following code perform ALL of the tasks below in C++:

-------------------------------------------------------------------------------------------------------------------------------------------

Implementation:

Overload input operator>> a bigint in the following manner: Read in any number of digits [0-9] until a semi colon ";" is encountered. The number may span over multiple lines. You can assume the input is valid.

Overload the operator+ so that it adds two bigint together.

Overload the subscript operator[]. It should return the i-th digit, where i is the 10^i position. So the first digit is the one's place (10^0) and the second digit is the ten's place (10^1).

Testing:

Build unit test for add. There is some testing but it is very incomplete. You will need to develop better tests cases here.

Build unit tests for subscript. There is a file for this but it has no tests.

Make sure your input operator works. This requires you to manually inspect the output. Test with different values and ranges.

You will need to update the Makefile - instructions are in the Makefile.

The command make tests will build and run the unit tests.

Create a main body, name the file add.cpp. See main.cpp (in svn/shared) as a starting point. The main reads from the file data1-1.txt and must do the following:

Test for success of opening the file in your program.

Read in two numbers into bigints and write both out separated by a blank line.

Add these together and write the result.

Then read in two more big numbers, adding them and writing the result until end of file.

All output must be labeled and neat.

The command make add will build and run this program.

Code:

------------------------------------------------------------------------------------------------------------------------------------------------------

Main.cpp

-----------------------------------------------------------------------------------------------------------------------------------------------------

#include

#include

#include

#include "Header.h"

int main() {

//open files

std::ifstream inFile;

inFile.open("dataFiles/mixed_input.txt");

  

//check if file even opened

if(!inFile.is_open()){

std::cout << "File did not open.\n";

return -1;

}

//stores some input data

char i;

inFile >> i;

std::cout << i << "\n";

  

while(!inFile.eof()){

std::cout << i << "\n";

inFile >> i;

}

  

BigInt bi(7925);

std::cout << bi << std::endl;

//bi.debug_print(std::cout);

  

BigInt bi1 ("7925");

std::cout << bi1 << std::endl;

//bi1.debug_print(std::cout);

  

//comparing bi and bi1.

// 1 - indicates EQUAL

// 0 - indicates UNEQUAL.

  

bool areEqual = (bi == bi1);

printf("\n Are bi and bi1 equal? %d\n",areEqual);

  

BigInt bi2 (1234);

std::cout << bi2 << std::endl;

//bi2.debug_print(std::cout);

  

//comparing the value after it has changed.

areEqual = (bi == bi2);

printf("\n Are bi and bi2 equal? %d\n",areEqual);

  

}

size_t strlen_(const char *s) {

return strlen(s);

}

//helps debug the print

void BigInt::debug_print(std::ostream& out) const {

  

out << " | ";

for(int i = MAX_DIGITS - 1; i >= 0; --i)

out << digit[i] << " | ";

}

//default

BigInt::BigInt():digit(){

  

}

//takes integer

BigInt::BigInt(int value){

  

//initialize all array elements to 0

int x = 0;

while (x < MAX_DIGITS) {

digit[x] = 0;

x++;

}

  

int i = 0;

while (value > 0){

i = i * 10 + (value % 10);

value /= 10;

}

  

//store the input into array

for (int x = 0; x <= MAX_DIGITS; ++x) {

digit[x] = i % 10;

i /= 10;

}

}

//takes char value

BigInt::BigInt(const char *value){

  

//initialize all array elements to 0

int x = 0;

while (x < MAX_DIGITS) {

digit[x] = 0;

x++;

}

  

//initialize size variable so it has number of digits in input.

size = strlen_(value);

  

//convert the character array to integer array and store the same value to it.

for(int i = 0; i < size; ++i){

this->digit[i] = *value - '0';

++value;

}

}

//overload operator== to compare

bool operator==(const BigInt &rhs , const BigInt &lhs){

  

//check to see if size of both inputs are equal, if not, it returns false.

if(lhs.size != rhs.size)

return false;

  

//compare every value.

for(int i = 0; i < lhs.size; i++){

if (lhs.digit[i] != rhs.digit[i])

return false;

}

return true;

}

//overload operator<<

std::ostream &operator<<(std::ostream & out, const BigInt & bi){

  

//return each index value to the out stream

for(int i = 0; i < bi.size; ++i )

out << bi.digit[i];

  

return(out);

}

//overload operator>>

std::istream &operator>>(std::istream & in, const BigInt & bi){

}

//overload operator+

BigInt operator+(const BigInt & rhs)const{

return lhs + rhs;

}

//overload operator[]

int BigInt::operator[](const BigInt &bi){

//10^0 represents the ones place in the number and [0] in the array and so on

return 0;

}

---------------------------------------------------------------------------------------------------------------------------------------------------------------------

Header.h

---------------------------------------------------------------------------------------------------------------------------------------------------------------------

#ifndef Header_h

#define Header_h

const int MAX_DIGITS = 500;

class BigInt {

  

private:

//array contains the BigInt.

int digit[MAX_DIGITS];

int size;

  

public:

//default constructor

BigInt();

  

//constructor that takes integer.

BigInt(int value);

  

//constructor that takes character array.

BigInt(const char *value);

  

//debug code

void debug_print(std::ostream& out) const;

  

// overloaded <<, ==, >>, +, []friend functions.

friend std::ostream &operator<<(std::ostream &out, const BigInt &bi);

friend std::istream &operator>>(std::istream &in, const BigInt &bi);

friend bool operator==(const BigInt &rhs, const BigInt &lhs);

int operator[](const BigInt &bi);

BigInt operator+(BigInt & rhs)const;

};

#endif /* Header_h */

Homework Answers

Answer #1

Please find the overloaded operators.

Since this looks like part of the assignment, I am not sure about the
constructor you are using in the BigInt class. and hence I have not provided the output.

I have used the below constructor and the overloaded operators corresponds to the same.

// constructor used in the program.
// initialize value array using integer input.
BigInt::BigInt(int x){

int i = 0;

// declare a vector digits.
std::vector<int> digits;

// store the input as a vector in the digits.
while (x)
{
digits.push_back(x % 10);
x /= 10;
i++;
}

// initialize size variable so that it contains number of digits in the input.
size = i;

// reverse the vector contents to get the correct value.
std::reverse(digits.begin(), digits.end());

// copy the contents to the value array.
std::copy(digits.begin(), digits.end(), value);
}

// Overloaded operator >>
std::istream &operator>>( istream &input, const BigInt &bi ) {
  
int i= 0;
// read till we get the ; operator.
while(input != ';'){
// since what we read from file will be string, converting the same to
// integer and storing in the array.
bi.value[i] = std::stoi(input);
i++;
}
return input;
}

// overloaded operator +
BigInt BigInt::operator+(const BigInt & rhs)const{

// carry variable.
int carry = 0;

// check the size of the current class.
int lsize = this->size;

// check the size of the rhs class to be added.
int rsize = rhs.size;

// longSum contains the final sum in string form.
std::string longSum;

int temp;

// Till either the size of lsize OR rsize is ZERO, continue.
while (lsize !=0 || rsize !=0){
int a = 0;
int b = 0;
// if still we have the elements to be added then fetch them in
// current class and the rhs class.
if (lsize != 0)
a = this->value[lsize];
if(rsize != 0)
b = rhs.value[rsize];

// add the values with carry.
temp = a + b + carry;

// if the sunm is of 2+ digits, then find the carry and store
// the current result in the longSum.
int t2 = temp % 10;
carry = temp/10;

// convert the sum to string before storing.
std::string ts = std::to_string(t2);

// append to the longSum
longSum.append(ts);

// decrement the lsize and rsize.
lsize--;
rsize--;
}

// at the end create a result BigInt class and return the same.
Big res((longSum));

return res;
}

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
How do I fix my error of binding on line 74? #include <iostream> #include <fstream> #include...
How do I fix my error of binding on line 74? #include <iostream> #include <fstream> #include <cctype> #include <cstring> #include <iomanip> using namespace std; #include "AvlTree.h" class WordCount { public:     char *word;     int *lines;     int count;     int size;     bool operator<(const WordCount &rhs) const {return strcmp(word, rhs.word) < 0;}     bool operator!= (const WordCount &rhs) const {return strcmp(word, rhs.word) != 0;}     WordCount():lines(NULL), count(0), size(0) {word = new char[1]; word[0] = '\0';}     friend ostream& operator<<...
Something is either messed up in my operator overload <<, covertopostfix function, or my main output....
Something is either messed up in my operator overload <<, covertopostfix function, or my main output. Cannot figure it out. please help. Please comment your changes too. Program below is supposed to be outputting like this: InFix is:   A+B-C Post fix is:   A B + C - InFix is:   A+C Post fix is:   A C + InFix is:   x*(y+z)-(w+t) Post fix is:   x y z + * w t + - InFix is:   A+B*(C+D)-E/F+G+H Post fix is:   A B C...
The program shown below reads in (N) values of time (hours, minutes, and seconds). If the...
The program shown below reads in (N) values of time (hours, minutes, and seconds). If the values for hours, minutes and seconds are a legal military time (i.e. 00 00 00 to 23 59 59) the program should display the formatted results (i.e. 12 34 56 should be displayed as 12:34:56). If there's an error for any of the entered values, an exception should be thrown and an error message should be displayed. Note, there are three exception conditions, one...
IN C++ format, Fill in the missing functions, using the concept of operator overloading. code: #include...
IN C++ format, Fill in the missing functions, using the concept of operator overloading. code: #include <string> #include <ostream> using namespace std; class Book { private:     string title;     string author;     unsigned isbn;     double price; public: /**Constructors*/    Book();    Book(string t, string a, unsigned i, double p);     /**Access Functions*/     string get_title();     string get_author();     unsigned get_isbn();     double get_price();     /**Manipulation Procedures*/    void set_title(string t);     void set_author(string a);     void set_isbn(unsigned...
CAN YOU PLEASE WRITE THIS CODE IN A DIFFERENT WAY 'EASIER AND BETTER' QUESTION Using C++...
CAN YOU PLEASE WRITE THIS CODE IN A DIFFERENT WAY 'EASIER AND BETTER' QUESTION Using C++ 11. Write a function that will merge the contents of two sorted (ascending order) arrays of type double values, storing the result in an array out- put parameter (still in ascending order). The function shouldn’t assume that both its input parameter arrays are the same length but can assume First array 04 Second array Result array that one array doesn’t contain two copies of...
- implement the Stack ADT using the linked list approach. Use C++ program language #include "StackLinked.h"...
- implement the Stack ADT using the linked list approach. Use C++ program language #include "StackLinked.h" template StackLinked::StackLinked (int maxNumber) { } template StackLinked::StackLinked(const StackLinked& other) { } template StackLinked& StackLinked::operator=(const StackLinked& other) { } template StackLinked::~StackLinked() {    clear(); } template void StackLinked::push(const DataType& newDataItem) throw (logic_error) {    } template DataType StackLinked::pop() throw (logic_error) { } template void StackLinked::clear() {    StackNode* t;    while ( top != NULL)    {        t = top;       ...
Data Structure in C++ I keep getting the same warning, and I cant seem to fix...
Data Structure in C++ I keep getting the same warning, and I cant seem to fix it.. Can you explain to me what I am doing wrong? Warning: dlist.cc: In function 'std::ostream& operator<<(std::ostream&, dlist&)': dlist.cc:66:10: error: invalid initialization of reference of type 'std::ostream& {aka std::basic_ostream&}' from expression of type 'dlist::node*' dlist.cc: In function 'dlist operator+(dlist&, dlist&)': dlist.cc:93:8: error: invalid operands of types 'dlist::node*' and 'dlist::node*' to binary 'operator+' dlist.cc:97:8: error: could not convert 'result' from 'int' to 'dlist' My code:...
Can someone please edit my code so that it satisfies the assignments' requirements? I pasted the...
Can someone please edit my code so that it satisfies the assignments' requirements? I pasted the codes below. Requirement: Goals for This Project:  Using class to model Abstract Data Type  OOP-Data Encapsulation You are asked to write an app to keep track of a relatively small music library. The app should load song information from a data file once the app is started. It should allow user to view, add, remove, and search for songs. The app should...
C++ See the provided specification files. Complete the implementation for each as a separate file. void...
C++ See the provided specification files. Complete the implementation for each as a separate file. void seen(std::string); If there is already a Word object in the Words list, then the number of occurrences for this word is incremented. If there is no Word object for this word already, create a new word object with occurrence =1, and insert this object into the list of Word objects. std::string getNextWord(); Returns the next word of the list and sets the currentItem pointer...
Please fill in the blank bolded below that would be the best choice for this program....
Please fill in the blank bolded below that would be the best choice for this program. #include <iostream> using namespace std; const int size = 100000; class TheBig { public: double operator[](int index) const {return (theData[index]);} private: double theData[size]; }; void firstToBeThe( ______________________________________________________) { for (int i = 0; i <size; i++) cout << value[i] <<endl; } int main() { TheBig one; firstToBeThe(one); }
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT