-1

I'm saving into an array the integers from the following content of a .txt file:

"15 ,12,10,19,22,2,20,17,5 ,2,20,25 ,12 ,10 ,23"

What I need to do is ignore the whitespace as well as commas, and save the numbers to an array. Simple, right? Not really, because the whitespace is occasional.

/* Here is my current code */
multiuseIndexPosition = 0;
while (fscanf(messageFilePointer, " %d,", &toBePushed) != EOF) {
    messageNumbersArray[multiuseIndexPosition] = toBePushed;
    multiuseIndexPosition++;
    printf("%d\n", toBePushed);
}

Unfortunately, this is causes an infinite loop that saves only the first number, 15. How can I save the integers from the .txt file? I've tried various ways using %*[^] without success.

This code works perfectly fine if the argument is "%d" and there are no white spaces in the .txt file.

D Mills
  • 51
  • 1
  • 7

1 Answers1

0

The issue that you are experiencing is due to the format that you have specified in your use of fscanf(). According to the documentation for fscanf(), which can be found by entering man fscanf into any terminal window, you are most likely encountering a matching error in which case fscanf() is returning a value of zero because "although there was input available, no conversions were assigned".

As for all numbers in your array being 15, that can easily be explained. Since fscanf() succeeded on the first iteration of your while-loop, 15 was saved to the address indicated by &toBePushed. Since all other iterations of your while-loop are instances in which fscanf() fails due to an inappropriately specified format, toBePushed maintains the same value assigned to it during the first iteration of the while-loop.

It seems like what you might need here is not fscanf(), but rather something else such as the function fgets() or gets(). Using either will enable your to read in a line from your text file and store that line in the form of a string. You can then be free to parse that string by breaking it up into smaller strings that are null terminated, which can then be converted into the integers that you want by using the string.h library function of strtol().

A.W.
  • 186
  • 1
  • 8
  • Thank you for your help (especially the infinite behavior explanation.) I resolved the issue by using more spaces in my format specifier: " %d , " – D Mills Feb 27 '14 at 02:01