Question: C++ Accurately adding large numbers using stacks You can use stacks to add very large numbers. You may use the stack template to implement stacks.

C++

Accurately adding large numbers using stacks

You can use stacks to add very large numbers. You may use the stack template to implement stacks.

Read in from a file two very large numbers and store them in the stacks, add the result.

Display the resulting answer.

Make sure your code is commented.

Sample run

Enter 1st number to be added

398877192309843792837423784

Enter 2nd number to be added

434820384038402384023840234

Answer is: 398877192309843792837423784 + 434820384038402384023840234 = 833697576348246176861264018

Press any key to continue

Try these pairs of numbers:

6000770088

99112233445

101

22233

Notice the simplicity of the last number, its easy to see if you are getting the right answer.

If you leave comments in the code so I can ask question if I need to that would be appreciated.

file.txt

398877192309843792837423784

434820384038402384023840234

I need help modifying this code below so that the numbers are stored in stacks and the output can look EXACTLY like the above sample run

#include

#include

#include

#include

using namespace std;

string findSum(string str1, string str2)

{

if (str1.length() > str2.length())

swap(str1, str2);

string str = "";

stack s1;

stack s2;

int n1 = str1.length(), n2 = str2.length();

//add them into stacks

for (int i = 0; i < n1; i++)

s1.push(str1[i]);

for (int i = 0; i < n2; i++)

s2.push(str2[i]);

int carry = 0;

for (int i = 0; i

{

int sum = ((s1.top() - '0') + (s2.top() - '0') + carry);

s1.pop();

s2.pop();

str.push_back(sum % 10 + '0');

// Calculate carry for next step

carry = sum / 10;

}

// Add remaining digits of larger number

for (int i = n1; i

{

int sum = ((s2.top() - '0') + carry);

s2.pop();

str.push_back(sum % 10 + '0');

carry = sum / 10;

}

// Add remaining carry

if (carry)

str.push_back(carry + '0');

// reverse resultant string

reverse(str.begin(), str.end());

return str;

}

int main()

{

string line;

ifstream myfile("file.txt");

int i = 1;

string s1, s2;

cout << "sample Run: " << endl;

cout << "Enter 1st number to be added ";

cin >> s1;

cout << "Enter 2nd number to be added ";

cin >> s2;

cout << "Answer is: " << findSum(s1, s2) << endl;

if (myfile.is_open())

{

while (getline(myfile, line))

{

cout << line << ' ';

if (line == "")

continue;

if (i == 1)

s1 = line;

else if (i == 2)

{

s2 = line;

cout << "Answer is: " << findSum(s1, s2) << endl;

}

i = i % 2 + 1;

}

myfile.close();

}

system("pause");

return 0;

}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!