You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用sscanf提取等号与分号间数字出错,求格式串问题排查

分析你的sscanf提取数字失败问题

Hey there! Let's dig into why your sscanf code is giving you that wonky id value instead of the number you're after.

First, let's recap your code and what's happening:

#include <stdio.h>
int main() {
    char name[20];
    int id;
    sscanf("tabid=12544787844;123", "%[^=]=%d", name, &id);
    printf(" name = %s id=%d\n", name ,id);
    return 1;
}

When you run this, you get name = tabid id=-340114044—definitely not the 12544787844 you wanted. Here's why:

The Core Issues

1. Integer Overflow (The Big Culprit)

Your target number 12544787844 is way too large for a standard int type. On most modern systems, int is 4 bytes, which only holds values between -2147483648 and 2147483647 (about ±2 billion). Your number is 12 billion—way outside that range. Trying to stuff this into an int triggers undefined behavior, which is why you're seeing that random negative garbage value.

2. Format String Robustness Gap (Minor, But Worth Fixing)

While the overflow is the main problem, your format string %[^=]=%d has a small gap: it doesn't explicitly account for the ; after the number. That said, %d will automatically stop reading at the first non-digit character (which is the ; here), so this isn't causing the bad id value—but adding it makes your code cleaner and more reliable.

Fixed Code

Here's how to get the correct result:

  1. Use a larger integer type (long long) that can hold big numbers like 12 billion.
  2. Match the type with the right format specifier (%lld instead of %d).
  3. Add a length limit to the name buffer to prevent overflow.
  4. Include the ; in the format string to enforce your input's structure.
  5. Check if sscanf successfully parsed both fields to catch errors.
#include <stdio.h>
int main() {
    char name[20];
    long long id;
    // %19[^=] ensures we don't overflow the name buffer
    int parse_result = sscanf("tabid=12544787844;123", "%19[^=]=%lld;", name, &id);
    
    if (parse_result == 2) {
        printf(" name = %s id=%lld\n", name, id);
    } else {
        printf("Failed to parse the input string\n");
    }
    return 0;
}

Running this will give you the expected output: name = tabid id=12544787844.

内容的提问来源于stack exchange,提问作者Anis_Stack

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:26:02