2

I am having problems with fscanf getting stuck in an infinite loop. {

char num;

FILE *filePtr;

if ((filePtr = fopen("filename.txt", "r")) == NULL)
{
    printf("File could not be opened");
}
else
{
    while (fscanf(filePtr, "%20[^ ,]", &num) != EOF)
    {
        displayFun(num);
    }

}

return 0;

The file input that I need it to read is: 0, 1, 2, 3, 16, 17, 1234, 5678, -201, 65534, 65535, 65536, -1

For some reason the code gets stuck in a loop and the first zero and wont continue on to the other numbers.

melpomene
  • 84,125
  • 8
  • 85
  • 148
Connor0429
  • 33
  • 2

1 Answers1

2

"%20[^ ,]" never consumes a , or space. They stay in filePtr for the next fscanf() call. Code needs to somehow read the , and space.

As @melpomene commented, reading text as a string into a char will not work,

Recommend to read an int and , instead.

int number;
while (fscanf(filePtr, "%d,", &number) == 1) {
    displayFun(num);
}
Community
  • 1
  • 1
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256