Is it possible to take variable length input from User

Discussion in 'C Programming' started by vaysagekv, Sep 9, 2012.

  1. vaysagekv

    vaysagekv Guest

    Hi,

    I have written a program to add two big numbers.So i want to take
    numbers as input from user.The number can be of any length (like 100
    digit or 1000 digit).
    What I am now doing is
    char str[100] ;
    scanf("%s",&str);// Or I can use fgets to check overflow.
    But the maximum charecters is limited to 100(in above case).
    Is it possible to take variable length input in C.

    Thanks
    vaysage.
    vaysagekv, Sep 9, 2012
    #1
    1. Advertising

  2. vaysagekv

    Stefan Ram Guest

    vaysagekv <> writes:
    >Is it possible to take variable length input in C.


    The following code does this with at most one call to malloc
    per read operation and no call of realloc. The length of
    the input is still limited by the size of »size_t«,
    »unsigned length«, and especially the size of the memory
    for objects with automatic storage duration. However,
    all those limitations are specified by the implementation
    - not by the program.

    #include <stdio.h>
    #include <stdlib.h>

    size_t count = 0;
    unsigned long depth = 0;

    char * doread( void )
    { int const c = getchar();
    if( c == EOF || c == '\n' || c == '\r' )
    { char * const result = malloc( count + 1 );
    if( result )result[ count ]= 0;
    return result; }
    else
    { ++count; if( count <= 0 )abort();
    ++depth; if( depth == 0 )abort();
    char * const buffer = doread();
    --depth;
    if( buffer )buffer[ depth ] = c;
    return buffer; }}

    char * read( void )
    { count = 0;
    depth = 0;
    return doread(); }

    int main( void )
    { char * result = read();
    if( result )
    { printf( "text = \"%s\".\n", result );
    printf( "count = (%lu).\n",( unsigned long )count );
    if( result[ 0 ])printf( "first = '%c'.\n", result[ 0 ]);
    if( result[ count > 0 ? count - 1 : 0 ])
    printf( "last = '%c'.\n", result[ count > 0 ? count - 1 : 0 ]);
    free( result );
    result = 0; }}
    Stefan Ram, Sep 9, 2012
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Mitchua
    Replies:
    5
    Views:
    2,737
    Eric J. Roode
    Jul 17, 2003
  2. =?Utf-8?B?Sm9obl9I?=
    Replies:
    1
    Views:
    2,769
    =?Utf-8?B?Sm9obl9I?=
    Jan 19, 2006
  3. Ted
    Replies:
    1
    Views:
    1,295
    Paul Uiterlinden
    Dec 6, 2006
  4. David Sanders
    Replies:
    4
    Views:
    422
    David Sanders
    Oct 30, 2007
  5. Raj
    Replies:
    0
    Views:
    154
Loading...

Share This Page