简体   繁体   English

如何使用 scanf 读取 float1##float2 形式的输入(即两个浮点数,由两个井号分隔)

[英]How to use scanf to read inputs which are in the form of float1##float2 (i.e., two float numbers separated by two pound signs)

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我需要通过以下方式处理输入输入两个用##分隔的浮点数:输入>> 3.19990##9.99921输出>> 3.19990 + 9.99921 = 13.19911

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.但是,通常不建议将scanf用于用户输入,因为它不会以直观的方式处理用户输入。 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.出于这个原因,通常最好使用 function fgets ,它总是一次读取整行,假设提供的 memory 缓冲区足够大。 After reading in one line of input as a string using fgets , you can then parse the string, for example using the function sscanf :使用fgets将一行输入作为字符串读取后,您可以解析该字符串,例如使用 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 );
}

In C its catered by default you just need to add Pound (#) signs in scanf().在 C 中,默认情况下您只需要在 scanf() 中添加磅 (#) 符号即可。 Eg:例如:

scanf(%f##%f,&x,&y);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM