carrayswhile-loopscanf

Unexpected behaviour when scanf used inside while loop to read an array


I wrote a program to read digits into array of integers a[100]. And the reading stops when the user enters a character 'e' or when array reached the maximum size.

But when the code is run, I got an unexpected behavior that, when user enters 'e' the scanning of digits into array terminates as I intended in program, but rest of the statements inside while loop including increment variable (i++) and printf functions I used to debug the the code until the first condition inside while's condition part become false.

#include <stdio.h>

int main(){
int a[100];
puts("Enter numbers(enter \"e\" to stop entring)\n");
int i=0;
scanf("%d",&a[i]);
while(i<100&&a[i]!='e'){
     i++;;
     scanf("%d",&a[i]);
     printf("\n -----> %d\n",i);
}
printf("\n\t i ---> %d\t\n",i);
return 0; 
}

Solution

  • Issues that I can think of:

    1. The incrementing of the array index needs to be updated.

      while(i<100&&a[i]!='e'){
           // When i 99 before this statement, i becomes 100 after the increment
           i++;;
           // Now you are accessing a[100], which is out of bounds.
          scanf("%d",&a[i]);
          printf("\n -----> %d\n",i);
      }
      

      what you need is:

      while(i<100&&a[i]!='e'){
          scanf("%d",&a[i]);
          printf("\n -----> %d\n",i);
          i++;;
      }
      
    2. If your input stream contains an e, the statement

      scanf("%d",&a[i]);
      

      won't read anything to a[i].

      You can fix that by:

      1. Read the input as a string.
      2. Check whether the string is e. If so, break out of the loop.
      3. If not, try to get the number from the string.

      Here's an updated version:

      char token[100]; // Make it large enough 
      while(i<100) {
          scanf("%s", token);
          if ( token[0] == 'e' ) // Add code to skip white spaces if you 
                                 // want to if that's a possibility.
          {
             break;
          }
          sscanf(token, "%d", &a[i]);
          printf("\n -----> %d\n",i);
          i++;;
      }