gpt4 book ai didi

c - 使用 sscanf 时忽略存储在变量中的一些字符

转载 作者:行者123 更新时间:2023-12-04 10:59:14 25 4
gpt4 key购买 nike

在下面的代码中,我需要从这样格式的行中提取 double 和字符串 "[double,double] 字符串"字符串以第一个非白色字符和 之后的任意数量的白色字符开始[

我确实关心正确加载数字,但不关心字符串(甚至可能为空)。

char *read;
size_t len=0;
double x,y;
int size;

getline(&read,&len,stdin);
char *name=(char*)malloc(strlen(read));
if(sscanf(read,"[ %lf, %lf ] %n",&x,&y,&size)!=2)
{
return 0;
}
sscanf(read,"%*.c%[^\n]s",size,name);

我已经实现了一切。我知道第二个 sscanf 不能像这样工作,只能在那里代表我的想法。有什么方法可以让大小变量成为不加载多少个字符的参数?我搜索了所有内容,唯一能找到的是定义了数字,这在这里没有帮助。

此外,我对编程还很陌生,所以请体谅我可能不知道基本的东西。

最佳答案

如果我理解您的问题并且您想分开,例如"[123.456, 789.34] Daffy Duck" 成两个 double ,名称使用 getlinesscanfname 分配存储空间,然后对 POSIX getline() 的单次调用和对 sscanf 的单次调用将名称读入临时数组,然后分配和复制到 name 将允许您精确调整 name 的大小按要求。

例如:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAXN 1024

int main (void) {

double x, y;
char *read = NULL, *name = NULL, tmp[MAXN];
size_t n = 0;

fputs ("input: ", stdout);
if (getline (&read, &n, stdin) == -1) {
fputs ("error: getline.\n", stderr);
return 1;
}

if (sscanf (read, " [%lf ,%lf ] %1023[^\n]", &x, &y, tmp) == 3) {
size_t len = strlen (tmp);
if (!(name = malloc (len + 1))) {
perror ("malloc-name");
return 1;
}
memcpy (name, tmp, len + 1);

printf ("x : %f\ny : %f\nname: %s\n", x, y, name);
free (name);
}
free (read);
}

没有必要对 malloc 的 return 进行强制转换,这是不必要的。参见: Do I cast the result of malloc?

另请注意,当参数 n = 0 如上所述时, getline() 将根据需要分配存储空间来处理您的输入行。因此,在调用 getline() 之后, read 已分配存储持续时间。您将需要释放 read 以避免内存泄漏,并且您不能简单地在 name 中返回指向 read 开头的指针,因为您必须保留指向 read 开头的指针才能对其进行 free

示例使用/输出

然后通过在您的 sscanf 格式字符串中包含适当的空格,您可以灵活地读取您的输入,而不管前导或中间空格,例如
$ ./bin/readxyname
input: [123.456, 789.34] Daffy Duck
x : 123.456000
y : 789.340000
name: Daffy Duck

输入中没有空格:
$ ./bin/readxyname
input: [123.456,789.34]Daffy Duck
x : 123.456000
y : 789.340000
name: Daffy Duck

在输入中使用任意空格:
$ input:  [        123.456    ,        789.34  ]           Daffy Duck
x : 123.456000
y : 789.340000
name: Daffy Duck

仔细检查一下,如果您还有其他问题,请告诉我。

关于c - 使用 sscanf 时忽略存储在变量中的一些字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58942298/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com