簡體   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)

我需要通過以下方式處理輸入輸入兩個用##分隔的浮點數:輸入>> 3.19990##9.99921輸出>> 3.19990 + 9.99921 = 13.19911

最簡單的解決方案如下:

#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 );
}

但是,通常不建議將scanf用於用戶輸入,因為它不會以直觀的方式處理用戶輸入。 例如,它並不總是讀取一整行用戶輸入,這可能會造成混淆並造成麻煩。

出於這個原因,通常最好使用 function fgets ,它總是一次讀取整行,假設提供的 memory 緩沖區足夠大。 使用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 );
}

在 C 中,默認情況下您只需要在 scanf() 中添加磅 (#) 符號即可。 例如:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM