Member Avatar for Marissak

I am trying to write a program to add large numbers with stacks. However, I do not know how to get each digit on to a stack individually.

This is what I mean:
For example, take the input 3784. How do I get the 3, 7, 8, and 4 as separate numbers so I can push them on to the stack starting with the first position.
The stack needs to look like this:
top:
4
8
7
3
bottom:

I am trying to implement an addingLargeNumbers() function which looks like this:

addingLargeNumbers()
	read the numerals of the first number and store the numbers corresponding to
	them on the stack;
	read the numerals of the second number and store the numbers corresponding
	to them on another stack;
	result = 0;
	while(!stack1.empty() || !stack1.empty()) //while at least one stack is not empty
		int x = stack1.pop() + stack2.pop();
		result.push(x); //pop a number from each nonempty stack and add them to result;
		push the unit part on the result stack;
		store carry in result;
	push carry on the result stack if it is not zero;
	pop numbers from the result stack and display them;

Not sure if that helps but...

Recommended Answers

All 6 Replies

Depends on the type you're reading..

If you store the user input as string, you can access the individual numbers(characters) just like you would with an array:

string test = "12345";
test[0]; // '1'
test[4]; // '5'

Would a loop where you take mod 10 then divide by ten work?
i.e

while(num>0)
{//some code to add to the stack num%10
num/=10;}
commented: yupp +3
Member Avatar for Marissak

I'm not sure because when I do

string ch;
	cin>> ch;
	int x = 0;
	for(int i = 0; i < ch.length(); i++) {
		x = x + ch[i];
	}

	cout << x;

using 56 I get 107.

But I'm going to try it in my program and see what happens.

That's because the ascii value of 5 is 53 and of 6 is 54. 53+54=107.
When casting a char to an int, you get the ascii value of that character.

You're better off using frogboy's suggestion, or substract 48 from ch.

(see www.asciitable.com)

Member Avatar for Marissak

Oh, I didn't realize they had ascii values. My mistake.

The problem is that I need to put each digit on stack1 and then pop the top and add it to the top of stack2 and then put the sum in stack.

But I'm going to try subtracting 48. I'm just concerned I wont be able to add them as integers.

Member Avatar for Marissak

I got it! Thanks for your help:icon_biggrin:

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.