-2

I'm trying to read text file using fscanf() with %[] specifier. File like this one:

qwety, qwe<

qwety,qwety.... qwety

So, I need to read only text without any separator like comma, space, dot.. Looking for answer said something like that, but it's doesn't work properly: successfully read only first word and go to never ending loop

char buff[1024];
while(!feof){
    fscanf(file, "%[a-z]", buff);
    puts(buff);
}

What should I do to solve this?

David C. Rankin
  • 81,885
  • 6
  • 58
  • 85
  • 2
    You will want to look at [**Why is while ( !feof (file) ) always wrong?**](http://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong). – David C. Rankin Apr 08 '18 at 09:25
  • No, problem with fscanf() only, cos I read always only one word instead of five – Vasya Vasya Apr 08 '18 at 09:32
  • `while (!feof)` will never loop. `feof` is a function which turns into a function pointer in this context. It never has a value that is false (`NULL`), so negating it is always false. Maybe that's just a typo, but then, that just shows that you should have provide a [mcve]. – Ulrich Eckhardt Apr 08 '18 at 10:01

1 Answers1

1

The problem is, after reading the first word into buff, the next characters in the file (your input buffer) are not a-z, so all subsequent calls to fscanf fail with a matching failure. To fix the problem, reverse the character class and use the assignment suppression operator ('*') to read and discard any non-a-z characters, e.g.

while (fscanf(file, "%1023[a-z]%*[^a-z]", buff) == 1)
    puts(buff);
David C. Rankin
  • 81,885
  • 6
  • 58
  • 85
  • `fscanf(file, "%1023[a-z]"...` and `fscanf(file, "%*[^a-z]"....` should be separated. This answer's `"%1023[a-z]%*[^a-z]"` consumption of non-letters requires a prior successful read of letters. This answer prints nothing if the first character of the file is a non-letter. – chux - Reinstate Monica Apr 08 '18 at 18:16
  • Well, point made, but I was simply working on the question asked, not all that could have been asked. If we were to separate, and condition a `break` on the first, we would end up in the same boat. Now we could `getchar()` and `ungetc()` as an initial test -- which would alleviate the problem. A `fgets` (or `getline`) with the 1st char test followed by `sscanf` would also make more sense from a robustness standpoint. – David C. Rankin Apr 08 '18 at 18:41