![]() |
Is it possible to take variable length input from User
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. |
Re: Is it possible to take variable length input from User
vaysagekv <kvvaysage@gmail.com> 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; }} |
| All times are GMT. The time now is 11:07 AM. |
Powered by vBulletin®. Copyright ©2000 - 2013, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.