Below is some simple code that should accept integer input from the console. It works fine until invalid (non integer) input is given.
1 #include <stdio.h>
2
3 int main()
4 {
5 int x = 0;
6 int inp = 0;
7 int nums[20];
8 int idx = 0;
9 for(;;){
10 printf("Enter an integer: ");
11 inp=scanf("%d", &x);
12 if(inp == 0){
13 printf("Error: not an integer\n");
14 }
15 else{
16 if(idx<20){
17 nums[idx] = x;
18 idx++;
19 }
20 }
21 }
22 return 0;
23 }
Here is output from gdb that shows me stepping through the program after entering the value "g". Look at how it jumps to line 18, and then fails to look for further input from the user.
Starting program: /Users/jeffersonhudson/xxxx/hw1
Enter an integer: g
Breakpoint 1, main () at hw1.c:12
12 if(inp == 0){
(gdb) n
13 printf("Error: not an integer\n");
(gdb) n
Error: not an integer
0x0000000100000ee4 18 idx++;
(gdb) n
10 printf("Enter an integer: ");
(gdb) n
11 inp=scanf("%d", &x);
(gdb) n
Breakpoint 1, main () at hw1.c:12
12 if(inp == 0){
(gdb)
This is the output of the program once you give it bad input:
Enter an integer: Error: not an integer
Enter an integer: Error: not an integer
Enter an integer: Error: not an integer
Enter an integer: Error: not an integer
Enter an integer: Error: not an integer
Enter an integer: Error: not an integer
Enter an integer: Error: not an integer
Enter an integer: Error: not an integer
Enter an integer: Error: not an integer
Enter an integer: Error: not an integer
Enter an integer: Error: not an integer
Enter an integer: Error: not an integer
Enter an integer: Error: not an integer
Enter an integer: Error: not an integer
Enter an integer: Error: not an integer
^C
Could someone please help me figure out what I am doing wrong here?