Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading in alphabet characters only - C

Tags:

c

scanf

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.

like image 626
mason Avatar asked Apr 13 '13 23:04

mason


People also ask

What is alphabetic character example?

the first letter of a word (especially a person's name) A, a. the 1st letter of the Roman alphabet. B, b.

How do you check if a character is not a letter in c?

C isalpha() The isalpha() function checks whether a character is an alphabet or not. In C programming, isalpha() function checks whether a character is an alphabet (a to z and A-Z) or not. If a character passed to isalpha() is an alphabet, it returns a non-zero integer, if not it returns 0.

What is an alphabetic symbol?

A letter is an alphabetic symbol such as A or a. There are 26 letters in the modern English alphabet. Among the world's languages, the number of letters ranges from 12 in the Hawaiian alphabet to 231 principal characters in the Ethiopian syllabary.

How do I get only the alphabet of a string?

Extract alphabets from a string using regex You can use the regular expression 'r[^a-zA-Z]' to match with non-alphabet characters in the string and replace them with an empty string using the re. sub() function. The resulting string will contain only letters.


2 Answers

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...
}
like image 99
Jonathan Leffler Avatar answered Oct 11 '22 18:10

Jonathan Leffler


I am fairly new to programming myself, but maybe this is what you are looking for. Hope it helps.

#include <ctype.h>

int i = 0;
FILE *fpin; 
char c, str[50];

while ((c = fgetc(fpin)) != EOF)
{
    if(isalpha(c))
        str[i++] = c;

}
str[i] = '\0';
// do something with str
like image 40
Venom Avatar answered Oct 11 '22 18:10

Venom