使用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:
- Use a larger integer type (
long long) that can hold big numbers like 12 billion. - Match the type with the right format specifier (
%lldinstead of%d). - Add a length limit to the
namebuffer to prevent overflow. - Include the
;in the format string to enforce your input's structure. - Check if
sscanfsuccessfully 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

