1

Sorry if it seems pretty simple to solve. But I am really new to C and have tried a lot, but I cant figure out how to stop the scanner from reading more integers than the max limit. I have a file which has 22 integers, but I want the array to store only 20 integers from the file. But still it's reading all integers. Any tip would be really valuable for me :/ Thanks a lot

int *array = malloc(20* sizeof(int));

while(fscanf(fp,"%d",&array[i])!=EOF)
    {

        printf("%d\n",array[i]); 
if(*array <= 20){
        i++;
    }
}
Sindre
  • 83
  • 8

4 Answers4

2

The code you have will increment i while the element in the first index of the array is less than or equal to 20. Which is possible if your first number (from the file) is less than or equal to 20.

if(*array <= 20){

You should do the following

while(i < 20) {
    if(fscanf(fp, "%d", &array[i]) != EOF) {
        printf("%d\n",array[i]); 
        i++;
    } else {
        break;
    }
}

Maybe later add some validation to make sure you read 20 numbers

if(i == 20) {
    ...
}
Logan Murphy
  • 6,120
  • 3
  • 24
  • 42
0

after your if:

else {
    break;
}
Rocky Pulley
  • 22,531
  • 20
  • 68
  • 106
0

see this example simply just change the counter of for loop and you'll get your job done

Community
  • 1
  • 1
Vikas
  • 432
  • 5
  • 18
-1

Try adding a break statement along with system.out.println statement.

 else 
{
  System.out.println("sorry!you are done");
  break;
  }

Hope this works!