gpt4 book ai didi

c - 在 C 中使用 sscanf() 获取可变数量的子字符串

转载 作者:行者123 更新时间:2023-11-30 14:39:08 30 4
gpt4 key购买 nike

所以我正在用 C 语言为汇编语言编写一个解析器。我有可以采用以下任一形式的宏:

# label
# dat variable_name, 3

如何使用单个 sscanf(或其他方法)将表达式拆分为各个组件。

例如标识符(用于标签和数据),变量(用于变量名称)和值(用于值)

最佳答案

How can I use a single sscanf (or another method) to split the expression into the various components.

使用"%n"记录扫描进度。

char label_dat[10 + 1];
char var_name[20 + 1];
int var_val;
int n1 = 0;
int n2 = 0;
// v-------v----v---- Tolerate trailing whitespace
sscanf(s, "# %10s %n %20s , %d %n", label_dat, &n1, var_name, &var_val, &n2);

// If scanning made it to `n1` and there was no more text
if (n1 && s[n1] == '\0') {
printf("Label '%s'\n", label_dat);
// If scanning made it to `n2` and there was no more text
} else if (n2 && s[n2] == '\0') {
printf("Data '%s', Name '%s', Value %d\n", label_dat, var_name, var_val);
} else {
puts("Bad input");
}

如果#,后面需要空格,则需要更多代码。

关于c - 在 C 中使用 sscanf() 获取可变数量的子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56241956/

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