我与此代码进行了为期 4 天的战斗:
unsigned long baudrate = 0;
unsigned char databits = 0;
unsigned char stop_bits = 0;
char parity_text[10];
char flowctrl_text[4];
const char xformat[] = "%lu,%hhu,%hhu,%[^,],%[^,]\n";
const char xtext[] = "115200,8,1,EVEN,NFC\n";
int res = sscanf(xtext, xformat, &baudrate, &databits, &stop_bits, (char*) &parity_text, (char*) &flowctrl_text);
printf("Res: %d\r\n", res);
printf("baudrate: %lu, databits: %hhu, stop: %hhu, \r\n", baudrate, databits, stop_bits);
printf("parity: %s \r\n", parity_text);
printf("flowctrl: %s \r\n", flowctrl_text);
它返回:
资源:5
波特率:115200,数据位:0,停止:1,
奇偶校验:
flowctrl:NFC
缺少数据位和奇偶校验!
实际上奇偶校验变量下的内存是'\0'VEN'\0',看起来第一个字符被sscanf过程以某种方式覆盖。
sscanf 的返回值为 5,这表明它能够解析输入。
我的配置:
- gccarmoneeabi 7.2.1
- 视觉工作室代码 1.43.2
- PlatformIO 核心 4.3.1
- PlatformIO 主页 3.1.1
- 库 ST-STM 6.0.0 (Mbed 5.14.1)
- STM32F446RE (Nucleo-F446RE)
我试过(没有成功):
- 使用 mbed RTOS 编译且不使用
- 变量类型 uint8_t, uint32_t
- gccarm 版本:6.3.1、8.3.1、9.2.1
- 使用另一个 IDE (CLion+PlatformIO)
- 在另一台计算机上编译(相同的配置)
实际上有什么帮助:
- 使变量静态
- 在 Mbed 在线编译器中编译
sscanf 的行为总体上是非常不可预测的,混合变量的顺序或数据类型有时会有所帮助,但通常以输出中的另一个缺陷结束。