I am doing a basic program that does calculations with very large numbers, what I do is read it as String
and the idea is that I multiply each digit of the number by a large number (for example 100000
).
#include <stdio.h>
#include <string.h>
#include <math.h>
int main( ) {
char cadena[1000];
char cadena2[1000];
scanf( "%s", cadena2 );
for( unsigned i = 0; i < strlen( cadena2 ); ++i ) {
cadena[i] = cadena2[i] - '0';
cadena[i] *= 100000;
cadena[i] = cadena[i] + '0';
}
printf( "%s", cadena);
return 0;
}
but logically it overflows and at the time of printing, that is, what is expected does not come out.
My question is how can I save a number so large that it should only be read as String
?
Thank you!
PS: I had already asked a question associated with this topic . Operation with a numeric value of a digit does not produce the expected result.
If you want to multiply each digit by
100000
, then your destination string must have a corresponding size:1000 * 100000
. The result of that is... just over 95M.We will use formations... but, in anticipation of size problems, we will create them dynamically (we may have problems with the size limit for the OS stack).
We have to take into account the size of the types ... a multiplication by
100000
does not fit in achar
, since the properchar
only admits in the range0
-255
. So we better useint
for these things.And finally, to make our lives easier, we'll use the
sprintf( )
. This function is similar toprintf( )
, but instead of writing to a file, it writes to a memory buffer (which we have to manage ourselves). It is exactly what we are looking for:If you scan a number as a string, you don't get the number itself but its character representation. Namely:
Thus, the number 123, stored as a string, results in the following number sequence (in hexadecimal):
30313200
.It's easy to see that, in this case, taking any of those characters and multiplying it by 100000 is not going to give you the expected result.
If you choose to store a number as a sequence of characters, you will have to implement all the mathematical operations involved, as the standard library has no use for this. You could also use a third party library.
That is, to add numbers you could do something like: