this program should add 2 integers in the range of 20 digits, but only 10 digits are allowed, else the sum would be incorrect. can anyone plz show me what's wrong with my codes? Here's what i got so far....

``````#include <cstdlib>
#include <iostream>

using namespace std;

int main(int argc, char *argv[])
{
char option=' ' ;
while ( (option != 'Q') and (option != 'q') )
{
cout << "Select : (C)ontinue (Q)uit:" ;
cin >> option ;
switch (option)
{
case 'C' : case 'c': //user chose to continue
{
cout << "Enter number in the range of 1-20 digits: " << endl;
char c[20] ;
cin >> c ;
int x = atoi (c) ; //convert into int
int num[20] ;
for (int i = 0; i < 20; i++)
{
char temp = c[i] ;
num[i] = atoi(&temp) ;
}
cout << "Enter 2nd number in the range of 1-20 digits: " << endl ;
char d[20] ;
cin >> d ;
int y = atoi(d) ;//convert into int
int num2[20] ;
for(int e = 0; e < 20; e++)
{
char temp2 = d[e] ;
num2[e] = atoi(&temp2) ;
}
int total = atoi(c) + atoi(d) ;
cout << "The total is " ;
cout << total << endl;
}
}
}

system("PAUSE");
return EXIT_SUCCESS;
}``````
4
Contributors
5
Replies
6
Views
10 Years
Discussion Span
Last Post by Lerner

You can not use atoi() because it returns an int which is probably too small to hold 20 digits. But you can use a 64-bit integer to hold the number and convert the string yourself.

>> char c[20] ;
Too small to hold 20 digits, you didn't leave room the the null terminator. Besides, use std::string if you are allowed to.

can u pls teach me how to use this method

``````int x;
x=temp - '0';``````

i think i created the wrong program..it should read each digit not convert it into integer...

Use link list to represent big digit.

i think i created the wrong program..it should read each digit not convert it into integer...

In that case just scrap whatever you posted and try again. If you want our help you will have to re-post the program's requirements, and don't just try to paraphrase it.

to convert the char representation of an int into an int you could do this:

char x = '4';
int y = x - '0';

where the second line means assign the difference of the ASCII (or other char set) value of zero from the ASCII (or other char set) value of x to y.

Remember if the string representation of the int is to be able to represent up to 20 digits it needs to have room for 21 char given the need for the null terminator.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.