sscanf(str1,“%s%d%f”,str2,#,&float1)产生意外结果

问题描述 投票:0回答:3

使用附带的库,如何从包含在数组中的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

c input scanf
3个回答
0
投票

删除printf中的运算符(&)的地址(“%s%d%.3f”,名称,&age和&rate);喜欢printf(“%s%d%.3f”,名称,年龄,比率);

当将&运算符放入printf()时,它将打印变量的地址


0
投票

您需要检查sscanf的返回值,以查看它是否能够找到并解析您在格式字符串中指定的内容。您还应该限制提取到固定大小缓冲区中的字符串的大小,以免缓冲区溢出。所以你想要类似的东西

while(true) {
    printf("Enter name, age and rate (exit to quit): ");
    if (fgets(input, sizeof(input), stdin) == 0) {
        // error or eof on the input
        exit(0); }
    if (sscanf(input,"%9s%d%f", name, &age, &rate) == 3)
        break;  // ok
    printf("I didn't understand that input\n");
}
printf("%s %d %.3f",name, age, rate);

0
投票

但是为什么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()需要&的运算符以获取变量的地址

© www.soinside.com 2019 - 2024. All rights reserved.