0
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<string.h>
#include<time.h>
int main(){

    int index=1;
    int *arr;
    int data;
    FILE *fp;
    int input,inp;
    arr=(int*)malloc(sizeof(int));
    fp=fopen("list2.txt","r");
    input=fscanf(fp,"%d",&inp);
    do{
        printf("%d",inp);
        if(inp!=','){
            arr[index-1]=inp;
            index++;
            arr=realloc(arr,(index)*sizeof(int));
        }
        input=fscanf(fp,"%d",&inp);

    }while(input!=EOF);
    fclose(fp);
    return 0;
}

I want to read a file that file contains-> 1,2,3,5,7,888, But my code goes into loop, why? How can I fixed this?

anonim
  • 57
  • 5
  • 2
    [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/q/25385173/1362568) – Mike Kinghan May 25 '20 at 18:23
  • 4
    Is it stalling on the comma in the data file? Do you need a `while` loop instead of a `do-while` and test `while(input == 1)` instead of `input != EOF`? If `fscanf` returns `0` your loop will not stop, and the input will stall. – Weather Vane May 25 '20 at 18:25
  • @WeatherVane if I write like this: while(input==1){ printf("%d",inp); if(inp!=','){ arr[index-1]=inp; index++; arr=realloc(arr,(index)*sizeof(int)); } input=fscanf(fp,"%d",&inp); } output is 1 – anonim May 25 '20 at 18:28
  • @user3121023 it works but why? – anonim May 25 '20 at 18:34
  • `fscanf(fp,"%d",&inp)` is only able to read an int, not a comma, this is why @user3121023 introduced the comma in the format to ask `fscanf` to also read it. When you use `fscanf` etc check the result, that means check it returns 1 because there is only one `%` in the format, if not that means it did nothing because you reach a non valid int or EOF. – bruno May 25 '20 at 18:38
  • Would be awesome if you could change the title to something more relevant in order to help others who might have the same issue. – Hasan Sefa Ozalp May 25 '20 at 23:36

0 Answers0