Hi guys.I need to make a small program with a function with this prototype: void f(char *a,char *b) that adds two numbers represented as strings without using conversion operators or other tricks.Thanks
You will still use at least char → int conversion.
Is it an assigment where you should forrlow instructions no matter what ridiculous it is or you can choose easier way?
Like i said it doesnt matter what i use ..i just need to have a function like this in my program and to avoid conversion operators or something like that.I will upload my code as soon as i get home.
From your description it is not clear where the result of the addition will be stored. It can be stored either in the string pointed by the first parameter or in the string pointed by the second parameter. Also it is not clear what to do if there will be an overflow. And at last the third question is how the numbers are stored. Whether the least significant digit is the first character in a string or is the last character in a string.
Well firstly it doesnt matter about overflow cuz it wont be large strings.Secondly the numbers are stored like this:the least significant digit is the last character in the string.And thirdly it doesnt matter where the addition will be stored i just need to see it on console.
ok, hint:
you should get two characters representing buts of same signifience achar and bchar
then:
1 2 3 4 5 6 7 8 9 10 11 12
//int result
//int factor;
//int overflow;
int x = char_to_int(achar) + char_to_int(bchar) + overflow;
overflow = (x>9)?1:0;
x %= 10;
//add digit to result. If result is integer:
//result = result + x*factor;
//factor *= 10;
//If it is string: char n = int_to_char(x);
//Push character into string somehow
//move to pair of more significant characters.
You should define function char_to_int (and possibly int_to_char)
Even if you will not define them as functions and will do manipulations with it in body of your function: you will still use conversions. You cannot go away from char → int conversion.
Why new just 20 chars? (without deleting them...) Such small amounts of memory are better allocated on the stack, for routine (or illustrative) purposes?
And why 19 rather than 20 for getline? getline will deal with the null terminator correctly if you use this:
1 2
char a[20] = ""; // be neurotic and zero buffer
std::cin.getline(a, 20); // or even sizeof(a)/sizeof(char)
It can be, but in process you will create your own version of atoi which will probably be less optimal and more error-prone than standard one. So why reinvent the wheel?