使用带有多个参数的 scanf

Use of scanf with multiple arguments

本文关键字:参数 scanf      更新时间:2023-10-16
cout<<"nt Please input the real and the complex part respectively :";
if(scanf("%d+i%d",&real_part,&complex_part)!=2)
{   
    if(real_part>0)
        cout<<"nt You have entered only the real part";
}

在这里,我想扫描一个复数。为此,上面的代码工作正常。如果我们输入单个数字,则将其分配为实数部分。但是我希望如果我只提供 i4 作为输入,它将被分配给complex_part保持真实部分不变(我已经初始化了两个变量)。有什么可能的方法可以做到这一点吗?

这就足够了:

if(scanf("%d", &real_part) == 1) /* If scanf succeeded in reading the real part */
{
    if(scanf("+i%d", &complex_part) == 1) /* If scanf succeeded in reading the imaginary part */
    {
        printf("Real part=%d, complex part=%dn", real_part, complex_part);
    }
    else
    {
        printf("Real part=%d, complex part=%dn", real_part, 0);
    }
}
else if(scanf("i%d", &complex_part) == 1) /* If scanf succeeded in reading the imaginary part */
{
        printf("Real part=%d, complex part=%dn", 0, complex_part);
}

函数 scanf 将返回成功填充的项目数。存储返回值并创建一系列处理每种情况的 if 语句:

const int filled = scanf( ...
if( filled == 1 )
{
    //only real
}
else if( filled == 2 )
{
    //both
}
else
{
    //none, handle error
}