gpt4 book ai didi

使用 sscanf 控制整个字符串

转载 作者:行者123 更新时间:2023-12-04 11:04:07 26 4
gpt4 key购买 nike

我需要在c中解析一个格式为“foo=%d”的字符串,我需要检查格式是否正确并读取int值。

我的初始代码是:

int foo_set = 0;
int foo;
if (sscanf(text, "foo=%d", &foo) == 1)
foo_set = 1;

但是代码应该拒绝诸如“foo=5$%£”之类的输入。这段代码行得通吗?

int foo_set = 0;
int foo;
char control;
if (sscanf(text, "foo=%d%c", &foo, &control) == 1)
foo_set = 1;

使用 control 字符代码检查没有额外的输入。有没有更好/更正确的方法来做到这一点?

谢谢

最佳答案

使用 %n 格式说明符来确定处理结束的位置并检查它是否与字符串的长度相匹配:

const char* text = "foo=4d";
int pos;
int foo;

if (sscanf(text, "foo=%d%n", &foo, &pos) == 1 &&
pos == strlen(text))
{
/* Valid as all of text consumed. */
}

C99 标准中格式说明符 n 的说明:

No input is consumed. The corresponding argument shall be a pointer to signed integer into which is to be written the number of characters read from the input stream so far by this call to the fscanf function. Execution of a %n directive does not increment the assignment count returned at the completion of execution of the fscanf function. No argument is converted, but one is consumed. If the conversion specification includes an assignment suppressing character or a field width, the behavior is undefined.

参见 https://ideone.com/d1rhPf 的演示.

关于使用 sscanf 控制整个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13701657/

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