sscanf() 是 scanf() 的变体,它用于从字符串中提取格式化数据,常用于解析输入字符串。
1️⃣ sscanf() 语法
int sscanf(const char *str, const char *format, ...);
str:要解析的字符串(必须是const char*,可以用c_str()转换string)。format:格式化字符串(指定数据类型,如%d、%s、%f)。...:可变参数,用于存储解析出的数据。
📌 返回值:
- 成功匹配的变量个数(即成功解析的数据个数)。
- 解析失败返回
0或EOF。
2️⃣ sscanf() 基本示例
🌟 示例 1:解析整数
#include <iostream>
#include <cstdio> // sscanf 需要引入
using namespace std;int main() {const char* str = "123 456";int a, b;sscanf(str, "%d %d", &a, &b);cout << "a = " << a << ", b = " << b << endl;return 0;
}
🖥 输出
a = 123, b = 456
✅ sscanf() 读取 str,并按照 %d %d解析两个整数。
3️⃣ sscanf() 解析不同数据类型
🌟 示例 2:解析多个数据类型
#include <iostream>
#include <cstdio>
using namespace std;int main() {const char* str = "42 3.14 hello";int num;float pi;char word[20];sscanf(str, "%d %f %s", &num, &pi, word);cout << "整数: " << num << endl;cout << "浮点数: " << pi << endl;cout << "字符串: " << word << endl;return 0;
}
🖥 输出
整数: 42
浮点数: 3.14
字符串: hello
✅ sscanf() 解析 整数、浮点数、字符串。
🌟 示例 3:解析 char 和 double
#include <iostream>
#include <cstdio>
using namespace std;int main() {const char* str = "A 2.718";char letter;double num;sscanf(str, "%c %lf", &letter, &num);cout << "字符: " << letter << endl;cout << "双精度浮点数: " << num << endl;return 0;
}
🖥 输出
字符: A
双精度浮点数: 2.718
✅ sscanf() 解析 字符和 double 类型。
4️⃣ sscanf() 解析特定格式的字符串
🌟 示例 4:解析日期
#include <iostream>
#include <cstdio>
using namespace std;int main() {const char* str = "2024-03-31";int year, month, day;sscanf(str, "%d-%d-%d", &year, &month, &day);cout << "Year: " << year << ", Month: " << month << ", Day: " << day << endl;return 0;
}
🖥 输出
Year: 2024, Month: 3, Day: 31
✅ sscanf() 解析 "2024-03-31" 为年、月、日。
5️⃣ sscanf() 解析复数
🌟 示例 5:解析复数 a+bi
#include <iostream>
#include <cstdio>
using namespace std;int main() {string num1 = "-3+2i";string num2 = "1+-4i";int a, b, c, d;sscanf(num1.c_str(), "%d+%di", &a, &b);sscanf(num2.c_str(), "%d+%di", &c, &d);cout << "num1: 实部 = " << a << ", 虚部 = " << b << endl;cout << "num2: 实部 = " << c << ", 虚部 = " << d << endl;return 0;
}
🖥 输出
num1: 实部 = -3, 虚部 = 2
num2: 实部 = 1, 虚部 = -4
✅ sscanf() 解析 复数的实部和虚部。
6️⃣ sscanf() 错误处理
🌟 示例 6:检查解析结果
#include <iostream>
#include <cstdio>
using namespace std;int main() {const char* str = "abc 123";int num;int count = sscanf(str, "%d", &num);if (count == 1) {cout << "成功解析: " << num << endl;} else {cout << "解析失败" << endl;}return 0;
}
🖥 输出
解析失败
✅ sscanf() 解析 abc 失败,因为它不是整数。
📌 结论
| 用法 | 格式符 | 示例输入 | 解析后结果 |
| 整数解析 |
|
|
|
| 浮点数解析 |
/ |
|
|
| 字符解析 |
|
|
|
| 字符串解析 |
|
|
|
| 复数解析 |
|
|
|
| 日期解析 |
|
|
|
🔹 sscanf() 是解析字符串数据的强大工具,常用于格式化输入解析,如处理用户输入、文件读取、日志分析等。
