gets () function for float value

5

I wanted to use the gets() function for a float value, or a similar function.

    
asked by anonymous 15.05.2016 / 12:16

2 answers

5

First, you should never use gets() for anything. It is a problematic function, not portable and considered obsolete. This is one of many things that teaches wrong out there.

The solution is to use the most appropriate variation of the scanf() function. Even this there is controversy if it should be used. You can even use it if you know what you are doing well, if it is a problem where it fits very well or a very simple problem. Otherwise the solution is to create a custom function or use fgets() , which is adopted by default by a lot of people.

    
15.05.2016 / 13:14
4

Never use the gets() function because it is impossible to tell in advance how many characters will be read, and therefore gets() will continue to store the characters read beyond the end of the buffer, which is extremely dangerous.

For this reason, the gets() function of the default library stdio.h has become obsolete since the C99 version of the C language.

The safe and standard alternative is the use of functions: scanf() and fgets() that allow you to control how many characters will be read into the buffer in advance.

Example with fgets() :

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

#define BUFFER_MAX_TAM   (32)

int main( int argc, char * argv[] )
{
    char buf[ BUFFER_MAX_TAM + 1 ];
    float f;

    printf( "Entre com um valor float: " );

    fgets( buf, BUFFER_MAX_TAM, stdin );

    f = atof( buf );

    printf( "Valor float lido: %f", f );

    return 0;
}

/* fim-de-arquivo */

Example with scanf() :

#include <stdio.h>

int main( int argc, char * argv[] )
{
    float f;

    printf( "Entre com um valor float: " );

    scanf( "%f", &f );

    printf( "Valor float lido: %f", f );

    return 0;
}

/* fim-de-arquivo */ 

I hope I have helped!

    
16.05.2016 / 14:47