VSCode中scanf函数无法正常工作问题求助
scanf无法正常读取输入,num被自动赋值的问题解决
问题代码
#include <stdio.h> int main(void) { int total=0; int i, num; printf("Sum of 0 to num, enter num: "); scanf("%d", &num); for(i=0; i<=num; i++) total += i; printf("Sum of 0 to %d: %d\n", num, total); return 0; }
问题现象
在VSCode中使用MinGW gcc编译、GDB调试时,按下F5执行程序后会卡顿一段时间,无法正常输入num值,直接输出类似内容:
**'[New Thread 5500.0x3a38] Sum of 0 to num, enter num:Sum of 0 to 1021: 521731'.**\
num被自动赋值为未输入的数值,从未输入过1021。
调试器输出信息
=thread-group-added,id="i1" GNU gdb (GDB) 7.6.1 Copyright (C) 2013 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html> This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. Type "show copying" and "show warranty" for details. This GDB was configured as "mingw32". For bug reporting instructions, please see: <http://www.gnu.org/software/gdb/bugs/>. Warning: Debuggee TargetArchitecture not detected, assuming x86_64. =cmd-param-changed,param="pagination",value="off" =cmd-param-changed,param="args",value="2>CON 1>CON <CON" [New Thread 19624.0x75c8] [New Thread 19624.0xc98] Loaded 'C:\WINDOWS\SysWOW64\kernel32.dll'. Symbols loaded. Loaded 'C:\WINDOWS\SysWOW64\KernelBase.dll'. Symbols loaded. Loaded 'C:\WINDOWS\SysWOW64\apphelp.dll'. Symbols loaded. Loaded 'C:\WINDOWS\SysWOW64\msvcrt.dll'. Symbols loaded. [New Thread 19624.0x75e4] Sum of 0 to num, enter num:Sum of 0 to 1021: 521731 The program 'C:\Users\chado\Yoonsw_C\Ch7\AddToNum.exe' has exited with code 0 (0x00000000).
解决方法
启用外部控制台交互
打开.vscode/launch.json,将"externalConsole"设置为true,让程序在独立控制台窗口运行,避免集成终端的输入输出重定向问题:{ "version": "0.2.0", "configurations": [ { // 其他配置项保留 "externalConsole": true, // 其他配置项保留 } ] }刷新标准输出缓冲区
在printf后添加fflush(stdout);,确保提示信息立即输出,避免缓冲区未刷新导致的交互异常:printf("Sum of 0 to num, enter num: "); fflush(stdout); scanf("%d", &num);升级GDB版本
当前使用的GDB 7.6.1版本过旧,存在兼容性问题,建议升级到最新版MinGW附带的GDB,提升调试稳定性。完善scanf错误处理
增加输入校验,确保输入失败时能及时终止或提示:if (scanf("%d", &num) != 1) { printf("输入错误,请输入整数\n"); return 1; }
内容的提问来源于stack exchange,提问作者차원우
相关产品推荐
相关产品推荐

