简体   繁体   English

C sscanf和字符串格式

[英]C sscanf and string format

I have a little bit of a problem while understanding the sscanf string formatting. 在了解sscanf字符串格式时,我遇到了一些问题。

I have that string stored in str : 192.168.0.100/act?bla= 我将那个字符串存储在str中192.168.0.100/act?bla=

I want with this code to have bla stored inside my "key" variable and the remaining stuff (after the '=') in my "buf" variable 我希望使用此代码将bla存储在我的“键”变量中,并将其余内容(在“ =”之后)存储在我的“ buf”变量中

char str[] = "192.168.0.100/act?bla=";
char key[20];
char buf[100];
sscanf(str, "%*[^?] %[^=] %s", key, buf);

The ? ? and = will not be consumed so include them in the format specifier: =将不会被使用,因此请将它们包含在格式说明符中:

sscanf(str, "%*[^?]?%[^=]=%s", key, buf);

See demo at http://ideone.com/YoRMh3 . 请参阅http://ideone.com/YoRMh3上的演示。

To prevent buffer overrun specify the maximum number of characters that can be read by each specifier, one less than the target array to allow for null termination, and ensure that both arrays were populated by checking the return value of sscanf() : 为了防止缓冲区溢出,请指定每个说明符可以读取的最大字符数,该字符数比目标数组少一个,以允许空终止,并通过检查sscanf()的返回值来确保两个数组都被填充:

if (2 == sscanf(str, "%*[^?]?%19[^=]=%99s", key, buf))
{
    printf("<%s>\n", key);
    printf("<%s>\n", buf);
}

In order to ensure that the buf value is not truncated, you can use the %n format specifier that populates an int indicating the position at which processing stopped (note the %n has no effect on the return value of sscanf() ). 为了确保buf值不被截断,可以使用%n格式说明符,该说明符填充一个int值,该整数值指示处理停止的位置(请注意, %nsscanf()的返回值没有影响)。 If the entire input was processed the end position is strlen(str) : 如果处理了整个输入,则结束位置为strlen(str)

int pos;
if (2 == sscanf(str, "%*[^?]?%19[^=]=%5s%n", key, buf, &pos) &&
    strlen(str) == pos)
{
    printf("<%s>\n", key);
    printf("<%s>\n", buf);
}

You can add the exptected characters so they will be read and ignored: 您可以添加受保护的字符,以便将其读取和忽略:

sscanf(str, "%*[^?]?%[^=]=%s", key, buf);

Note that '?' 注意 '?' and '=' are still in the stream and aren't read after [^=] is processed. 和'='仍在流中,并且在处理[^=]之后不会被读取。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM