How to read an integer with no limit of digits in C

Asked

Viewed 453 times

-1

It has some way of reading an integer from the keyboard without limit control of digits. Like I need to pass a giant number via keyboard to a variable and then pass all the digits of that number to us from a list. Any suggestions?

  • 1

    Yes, read in buffer controlled (maybe only 100 digits at a time?) and send to a data structure called BigInt.

  • How so? use function fgets()

  • That question has already passed through here, unfortunately I could not find it

1 answer

1


You can use a buffer of chars large enough to accommodate the integers as a string.

Operations with large integers can be done using a library from GNU calling for gmplib.

Here is an example where the two arguments (large integers) passed to the main() are multiplied and their result displayed on the screen:

#include <gmp.h>
#include <stdio.h>

#define MAX_BUF_LEN    (128)

int main( int argc, char * argv[] )
{
    char res[ MAX_BUF_LEN ];

    mpz_t a, b, c;

    mpz_init(a);
    mpz_init(b);
    mpz_init(c);

    mpz_set_str( a, argv[1], 10 );
    mpz_set_str( b, argv[2], 10 );

    mpz_mul( c, a, b );

    mpz_get_str( res, 10, c );

    printf("%s\n", res );

    mpz_clear(a);
    mpz_clear(b);
    mpz_clear(c);

    return 0;
}

compiling:

$ gcc -lgmp -Wall bigintmul.c -o bigintmul

Testing:

$ ./bigintmul 1234567890123456789012345678901234567890 9876543219876543219876543219876543210

Exit:

12193263124676116335924401657049230176967230591384377380136092059011263526900

Checking:

inserir a descrição da imagem aqui

Browser other questions tagged

You are not signed in. Login or sign up in order to post.