Gets() function for float value

Asked

Viewed 691 times

6

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

  • Did any of the answers solve your problem? Do you think you can accept one of them? If you haven’t already, see [tour] how to do this. You would help the community by identifying the best solution for you. You can only accept one of them, but you can vote for any question or answer you find useful on the entire site.

  • By definition the gets function reads a string, so after reading the string you need to do the conversion to float. Be sure to consider the observations already made on the safety of this function.

2 answers

6

First, you should never use gets() for nothing, it is a problematic function, not portable and considered obsolete. This is one of the many things they teach wrong around.

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

Anyway in real codes that are not prototypes or exercises people use a very sophisticated form of data entry.

5

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

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

The safe and in default alternative is the use of functions: scanf() and fgets() that allow control of how many characters will be read into the buffer with anticipation.

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’ve helped!

  • 1

    For greater safety you must at all times validate the value returned by most functions with prototype in <stdio.h>: if (fgets(buf, sizeof buf, stdin) == NULL) /* erro */; or if (scanf("%d%d%d", &one, &two, &three) != 3) /* erro */;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.