sscanf(str1,“%s%d%f",str2,#,&float1)产生意外结果 [英] sscanf(str1, "%s %d %f", str2,&num,&float1) producing unexpected results
问题描述
使用所包含的库,如何从存储在数组中的fget的输入中分离出包含名称,年龄和比率的字符串?
Using the included libraries, how do I separate a string containing a name, age, and rate, from the input from fgets stored in an array?
我需要修改字符串,年龄和格式化速率以显示3个小数位.之后,我需要将这些变量的新结果存储在单个char数组中.到目前为止,这就是我所拥有的.我不知道是什么原因导致sscanf()给我意外的结果或如何解决该问题
I need to modify the string, age, and format the rate to show 3 decimal places. After that, I need to store the new result of these variables in a single char array. This is what I have so far. I don't know what is causing sscanf() to give me the unexpected results or how to fix it
#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
The name is displayed properly, but the age is some random large number and the rate is displayed as 0.000
推荐答案
删除printf(%s%d%.3f",名称,& age,& rate)中的运算符(&)的地址;喜欢 printf(%s%d%.3f",名称,年龄,费率);
Remove the address of operator (&) in printf("%s %d %.3f",name, &age, &rate); like printf("%s %d %.3f",name, age, rate);
当您放置& printf()中的运算符打印变量的地址
When you put & operator in printf() It prints the address of the variable
但是为什么scanf()需要&运算符?
But why does scanf() require the & operator?
让我们看一个例子:
int main()
{
int *ad,var;
ad=&var;
*ad=10;
printf("%d",var);
return 0;
}
它将打印10
让我们看看具有功能的另一个示例:
let see another Example with function:
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
因此,如果要在函数中修改变量,则可以通过引用传递变量
So,If you want to modify a variable in function You would pass the variable by reference
因此,scanf()需要&运算符以获取变量的地址
So,scanf() needs & of operator to get the address of variable
这篇关于sscanf(str1,“%s%d%f",str2,#,&float1)产生意外结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!