使用具有多个参数的scanf

时间:2016-01-24 10:29:13

标签: c++ algorithm

cout<<"\n\t Please input the real and the complex part respectively :";
if(scanf("%d+i%d",&real_part,&complex_part)!=2)
{   
    if(real_part>0)
        cout<<"\n\t You have entered only the real part";
}

这里我想要扫描一个复数。为此,上面的代码工作正常。如果我们输入单个数字,它被指定为真实部分。但是如果我只给出 i4 ,我想要它将被分配给complex_part的输入保持不变的实部(我已经初始化了两个变量)。有没有可能的方法来实现它?

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:1)

这就足够了:

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=%d\n", real_part, complex_part);
    }
    else
    {
        printf("Real part=%d, complex part=%d\n", 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=%d\n", 0, complex_part);
}