No, for that you would need to allocate the array with malloc/realloc. A more typical approach is to declare a reasonably large input buffer and just limit the user input to that. So say you expect the use to enter 10 characters. Declare an array of 64 and it should be more than ample, etc. Anyway, a much safer way to read input, incidentally, is by using fgets. You don't need do hard-code the array size in the string, and integers/floats can be converted with atoi/strtol/atof. The drawback is that fgets and scanf create problems when used together (eg: scanf leaves the newline in the input buffer while fgets stores it).
I put together a little example, though I may have goteen a bit carried away...
Code:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
char* getline( char* buf, size_t max, FILE* inf )
{
char* fnd, * ret = fgets( buf, max, inf );
if( ret != 0 )
{
/*
Remove the newline
*/
fnd = strchr( ret, '\n' );
if( fnd )
*fnd = 0;
}
/*
An error/eof occured, set first character to 0,
making sure that there is room, though, first
*/
else if( max )
{
*buf = 0;
}
return ret;
}
int text_to_double( const char* dat, double* ret )
{
char* ptr;
*ret = strtod( dat, &ptr );
if( *dat == 0 || *ptr != 0 )
{
*ret = 0;
return 0;
}
return 1;
}
int text_to_integer( const char* dat, int* ret )
{
char* ptr;
*ret = strtol( dat, &ptr, 0 /*guess*/ );
if( *dat == 0 || *ptr != 0 )
{
*ret = 0;
return 0;
}
return 1;
}
int main(void)
{
const size_t size = 128;
char buffer[ size ], temp[ size ];
int mode, i;
double d;
enum { text_mode = 0, integer_mode, double_mode, invalid_mode };
for( ;; )
{
printf( "Enter some text (press [ENTER] to exit) > " );
getline( buffer, size, stdin );
if( buffer[ 0 ] == 0 )
{
break;
}
for( ;; )
{
printf( "Mode? (0) Text (1) Integer (2) Float > " );
if( !text_to_integer( getline( temp, size, stdin ), &mode ) )
{
puts( "Error: expected integer. Please try again." );
}
else if( mode >= invalid_mode )
{
puts( "Error: invalid option. Please try again." );
}
else
{
break;
}
}
if( mode == text_mode )
{
printf( "You entered the text: '%s'\n", buffer );
}
else if( mode == integer_mode )
{
if( !text_to_integer( buffer, &i ) )
{
printf( "Sorry, '%s' is not a valid integer value!\n", buffer );
}
else
{
printf( "You entered the number '%d'\n", i );
}
}
else if( mode == double_mode )
{
if( !text_to_double( buffer, &d ) )
{
printf( "Sorry, '%s' is not a valid floating point value!\n", buffer );
}
else
{
printf( "You entered the floating point number '%f'\n", d );
}
}
}
return 0;
}
Sorry if it has bugs, it's just an example, really. But my point is simply that scanf really isn't necessary in most cases.
EDIT: Whoops should have been "press ENTER" not "press SPACEBAR".