使用带有多个参数的 scanf
Use of scanf with multiple arguments
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
}
相关文章:
- 如何反转整数参数包
- 使用C++库在Android项目中修改gradle中的cmake参数,用于插入指令的测试
- 如何使用默认参数等选择模板专业化
- 模板参数替换失败,并且未完成隐式转换
- 具有默认模板参数的多态类的模板推导失败
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 函数调用中参数的顺序重要吗
- 部分定义/别名模板模板参数
- 模板-模板参数推导:三个不同的编译器三种不同的行为
- 使用不带参数的函数访问结构元素
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 如何在OMNET++中指定与命令行参数组合的输出文件名
- 如何使用Luacneneneba API正确读取字符串和表参数
- 在派生函数中指定void*参数
- 为什么我应该在scanf()-家族成员中包含一个长度修饰符作为参数?有什么好处?使用长度修改器进行扫描的作用
- 不能使用嵌套结构中的联合元素作为 scanf() 的参数来存储所需的值
- 使用带有多个参数的 scanf
- 我们是否可以创建一个类似scanf的函数,当所有参数都填充时返回true,否则返回false,而不循环遍历所有变量?
- Scanf需要额外的参数