c - sscanf(str1, "%s %d %f", str2,&num,&float1) 产生意外结果
问题描述
使用包含的库,如何将包含名称、年龄和速率的字符串与存储在数组中的 fget 的输入分开?
我需要修改字符串、年龄和格式以显示 3 个小数位。之后,我需要将这些变量的新结果存储在单个 char 数组中。这就是我到目前为止所拥有的。我不知道是什么导致 sscanf() 给我意外的结果或如何解决它
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
#define SIZE 10
#define SIZE2 40
int main(){
char input[SIZE2]={};
char name[SIZE]={};
int age = 0;
float rate = 0;
printf("Enter name, age and rate (exit to quit): ");
fgets(input, SIZE2, stdin);
sscanf(input,"%s %d %f", name, &age, &rate);
printf("%s %d %.3f",name, &age, &rate);
return 0;
}
名称显示正常,但年龄是一些随机的大数字,比率显示为 0.000
解决方案
printf("%s %d %.3f",name, &age, &rate);中去掉运算符(&)的地址 比如 printf("%s %d %.3f",name, age, rate);
当您将 & 运算符放入 printf() 时,它会打印变量的地址
但是为什么 scanf() 需要 & 运算符?
让我们看一个例子:
int main()
{
int *ad,var;
ad=&var;
*ad=10;
printf("%d",var);
return 0;
}
它将打印 10
让我们看看另一个功能示例:
void sum(int *sum,int a,int b)
int main()
{
int a=10,b=10,c;
sum(&c,a,b);
printf("%d",c);
return 0;
}
void sum(int *sum,int a,int b)
{
*sum=a+b;
}
它将打印 20
所以,如果你想修改函数中的变量,你可以通过引用传递变量
所以,scanf() 需要 & of 运算符来获取变量的地址
推荐阅读
- html - Facebook Bug 解码器 - 图像元数据正在获取“不是有效的 URL”。错误
- excel - Excel VBA剪切和粘贴反复风靡一时
- c# - 有没有办法改变字体或制作很酷的艺术作品(如 ASCII)?
- linux - 为什么我只能从一侧执行 TCP 握手?
- c# - 返回任务
从异步方法无需等待 - android - 应用程序被杀死时未调用 onDispose 回调
- mysql - Google 条形图在没有可用数据的情况下填充空白
- android - Android 应用程序中的单例类或扩展 ThreadPoolInstance 的应用程序
- amazon-web-services - AWS 使用 Cloudfront 增强托管性能
- python - pyplot:在轴上添加点投影