Is it possible to take variable length input from User

V

vaysagekv

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.
 
S

Stefan Ram

vaysagekv said:
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; }}
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top