Reading in alphabet characters only - C

c, scanf

Solution

You're nearly there; the scan set should be used, but the scan set does not have an `s` conversion too.

while (fscanf(fpin, "%49[a-zA-Z]", str) == 1) {

The 49 prevents buffer overflows (and yes, it has to be one less than the dimension of the array).

Of course, this works for the first word; you then need to skip over the non-word characters before you can read the next word, so you might have:

while (fscanf(fpin, "%49[a-zA-Z]", str) == 1)
{
    ...do something with word in str...
    if (fscanf(fpin, "%49[^a-zA-Z]", str) != 1)
        ...decide what to do...
        ...but remember one problem might be that the 'word' was too long...
}

Problem

I'm opening a text file and want to read in the alphabet words only. So for example if I had a text file with "Hello-World Hey". I'd like to read the words "Hello", "World", "Hey". The problem is I'm not sure what the "format specifier" should be for this output. I've tried countless combinations but none worked as hoped. ``` FILE *fpin; char str[50]; while (fscanf(fpin, "%s[a-zA-Z]", str) != EOF) { // do something with str } ``` Any help would be much appreciated! Thanks.

Original source