首页 > 解决方案 > 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

标签: cinputscanf

解决方案


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 运算符来获取变量的地址


推荐阅读