Search code examples
cextractdigits

Extracting the digits between letters in a file C


I have a text file which includes randomly entered numbers and letters.

I need to extract the numbers in file but not all of them, only the first five digits.

My text file has the characters:

hg34h2g45hjk36jk6jkh34jkl34hl378l59k0567l60hlh67h98j496j46k90k1hjk1

So I wrote this code,

#include <stdio.h>
#include <conio.h>
#include <ctype.h>

int main()
{
    int c;
    FILE *fp;
    fp = fopen("file1.txt", "r");

    while ((c =fgetc(fp)) != EOF )
    {
        if (isdigit(c))
        {
            putchar(c);
        }
    }
    getch();
}

when i run the code, it shows all of digits in the file. This is the output:

342453663434378590567606798496469011 Blockquote

I'm stuck at there, what should i do from now on?

EDIT: Main problem has been solved, but is it possible to assign the output to a desired variable?


Solution

  • just count upto 5:

    #include <stdio.h>
    #include <conio.h>
    #include <ctype.h>
    
    int main()
    {
        int c;
        int count =0;
        FILE *fp;
        fp = fopen("file1.txt", "r");
    
        while (((c =fgetc(fp)) != EOF) && count <5 )
        {
            if (isdigit(c))
            {
                putchar(c);
                count ++;
            }
        }
        getch();
    }