Calculating two numbers with length 1000

Hello!
My program accepts the following template as input:

number1 + number2 ?

and returns the addition of the two.
As seen I used three char arrays, but somewhere I've made a mistake.
Thanks !
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#include <iostream>
using namespace std;

int main() {
	const int size = 1000;
	const int Size = 1001;
	char c;
	char Number1[size] = {'\0'};
	char Number2[size] = {'\0'};
	char Result[Size];
	int digIdx = 0;
	int numDigResult = 0;
	int residue = 0;
	int i = 0;

	do {
		 cin >> Number1[i];
		++i;
	} while(size >= i);

	int j = 0;

	do {
		cin >> Number2[j];
		++j;
	} while(size >= j);


	do {
		cin >> c;
	} while(c != '?');

	int numDig1 = sizeof(*Number1)/sizeof(char);
	int numDig2 = sizeof(*Number2)/sizeof(char);
	int digSum = 0;

	if(numDig1 >= numDig2) 
		digSum = numDig1+1;
	else if(numDig1 < numDig2)
		digSum = numDig2+1;


	if( c == '?') {

	for(int i = 0; i<=digSum ; ++i) {
		++digIdx;
		digSum = residue;
		(Number1[numDig1 - digIdx])-'0';
		(Number2[numDig2 - digIdx])-'0';
		if( 0 <= (numDig1 - digIdx) )
			digSum += (Number1[numDig1 - digIdx])-'0';
		if( 0 <= (numDig2 - digIdx) )
			digSum += (Number2[numDig2 - digIdx])-'0';
		Result[numDigResult - digIdx] = digSum % 10;
		residue = digSum / 10;
		if( ((numDig1 - digIdx) >= 0) && ((numDig2 - digIdx) >= 0) && (residue == 0) ) break;
	}
	for(digIdx = 0; digIdx <=numDigResult-1; ++digIdx)
		cout << Result[digIdx]-'0';
	}
}
Last edited on
Are you trying to read 1000 digit numbers?
1
2
3
4
do {
	cin >> Number1[i];
	++i;
} while(size >= i);

This will force the user to enter 1001 chars. I don't think that is what you want.

Line 48 and 49 doesn't do anything.

And this will not work
int numDig1 = sizeof(*Number1)/sizeof(char); *Number1 is a char and sizeof(char) is always 1 so numDig1 (and numDig2) is always 1.
Uh, thank you, I totally forgot about the two lines / 48 & 49 / .... :D
I modified the two whiles, so when they meet + or ? - break.
Should I use atoi to get the length ?
Also is there a way we can communicate faster ?
Thanks again ;) !
No you should not use atoi to get the length. Doesn't i an j already contain the lengths?
Got that!
Thank you :)
Topic archived. No new replies allowed.