c++ - 使用带有多个参数的 scanf

标签 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 的输入保持实部不变(我已经初始化了两个变量)。有什么办法可以实现吗??

最佳答案

这就足够了:

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

关于c++ - 使用带有多个参数的 scanf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34974667/

相关文章:

c++ - Boost::asio::write上的互斥不起作用

c++ - 静态库缺少 `__imp_` 符号

c++ - 将适当数量和类型的参数传递给函数

c# - 算法:两个正则表达式的交集

c++ - 作用域、数组和堆

c++ - 将字符串转换为 double - 精度丢失

计算二进制数字范围内 1 的个数的算法

python - SPOJ 在 C 中接受相同的算法,在 Python 中超过时间限制

algorithm - edmonds karp 最大流算法中缺少一些路径

javascript - 将一个数字转换为另外两个数字的总和,使差异最小