Home > OS >  How to use scanf to read inputs which are in the form of float1##float2 (i.e., two float numbers sep
How to use scanf to read inputs which are in the form of float1##float2 (i.e., two float numbers sep

Time:09-19

I need to handle inputs in the following ways Enter two float numbers separated by ##: Input >> 3.19990##9.99921 Output>> 3.19990 9.99921 = 13.19911

CodePudding user response:

The simplest solution would be the following:

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

int main( void )
{
    float f1, f2;

    //prompt user for input
    printf( "Please enter two floating-point numbers separated by ##: " );

    //attempt to read and parse user input
    if ( scanf( "%f##%f", &f1, &f2 ) != 2 )
    {
        printf( "Input error!\n" );
        exit( EXIT_FAILURE );
    }

    //print the result
    printf( "You entered the following two numbers:\n%f\n%f\n", f1, f2 );
}

However, using scanf for user input is generally not recommended, as it does not behave in an intuitive manner with user input. For example, it does not always read an entire line of user input, which can be confusing and cause trouble.

For this reason, it is usually better to use the function fgets, which always reads an entire line at once, assuming that the supplied memory buffer is large enough. After reading in one line of input as a string using fgets, you can then parse the string, for example using the function sscanf:

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

int main( void )
{
    char line[200];
    float f1, f2;

    //prompt user for input
    printf( "Please enter two floating-point numbers separated by ##: " );

    //attempt to read one line of user input
    if ( fgets( line, sizeof line, stdin ) == NULL )
    {
        printf( "Input error!\n" );
        exit( EXIT_FAILURE );
    }

    //attempt to parse the input
    if ( sscanf( line, "%f##%f", &f1, &f2 ) != 2 )
    {
        printf( "Parse error!\n" );
        exit( EXIT_FAILURE );
    }

    //print the result
    printf( "You entered the following two numbers:\n%f\n%f\n", f1, f2 );
}

CodePudding user response:

In C its catered by default you just need to add Pound (#) signs in scanf(). E.g:

scanf(%f##%f,&x,&y);
  •  Tags:  
  • c
  • Related