Debug Assertion Failed错误排查:scanf_s格式化输入异常问题
解决 Debug Assertion Failed: _format_parser.error_code() == 0 错误
错误根源
你代码里的核心问题是**scanf_s使用了错误的格式符**:
- 读取浮点数时,你写了
scanf_s("%.1f", &p);,但%.1f是给printf用的输出精度控制格式,scanf_s(包括标准scanf)读取浮点数只需要用%f,不能加.1这种精度修饰,这会直接导致格式解析失败,触发断言错误。 - 另外代码里的
printf字符串直接写换行(比如原代码里的"Please enter article characteristics.\n"写成了直接换行),虽然不会引发断言错误,但属于不规范写法,建议统一用\n表示换行。
修正后的代码
#include <stdio.h> int main() { int a, n; float p; printf("Please enter article characteristics.\n"); printf("Article Number: "); scanf_s("%d", &a); printf("Number of pieces: "); scanf_s("%d", &n); printf("Price per piece: "); scanf_s("%f", &p); // 此处将%.1f改为%f printf("\n\tArticle Number\tQuantity\tPrice Per Piece\n"); printf(" %d\t\t%d\t %.1f Dollar\n", a, n, p); return 0; }
额外说明
如果你用的是MSVC编译器的scanf_s,对于浮点数的读取,%f是正确的格式符,不需要额外参数(只有读取字符串时才需要指定缓冲区大小)。修正后就能正常读取所有输入,不会再触发断言错误。
内容的提问来源于stack exchange,提问作者Jwill
相关产品推荐
相关产品推荐

