#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;
}
This is my C code, and when I try to enter num value through scanf() function in vscode, it isn't working. It takes some time to executing the file after I pressed 'f5', and the output is like this:
**'[New Thread 5500.0x3a38] Sum of 0 to num, enter num:Sum of 0 to 1021: 521731'.**\
I never entered 1021 to num, but it was entered automatically.
Please help how to solve this problem.
////////////////////
I tried 'error handling' codes for 'scanf', but it is still not working.
My code builder is 'MinGW gcc.exe', and debugger is GNU gdb.
Below is output of the debugger.
=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).
Please help if you don't mind. Thank you.
scanf()(or any input function) correctly unless you Check The Return. What happens if the user slips and presses'r'reaching for'4'? You needif (scanf ("%d", &num) != 1) { /* handle the error */ }Learn that now it will save you no end of grief (and infinite loops) later. Also, get in the habit of fully guarding all code blocks with{ ... }. In your casefor(i=0; i<=num; i++) { total += i; }. Yes it will take 1-extra line and 2-extra characters, but it too will save you no end of grief later... Good luck with your coding!i=0; i<=num;is likely wrong since this iteratesnum+1times and notnumtimes as might have been expected.10followed by [Enter]. The problem is elsewhere.numwas uninitialised so when the uncheckedscanffails, its value is indeterminate.