Question

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?

Was it helpful?

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();
}

OTHER TIPS

Use a variable to keep track of count. When the count reaches 5, break out of the loop as shown below.

int c;
FILE *fp;
fp = fopen("file1.txt", "r");
int count = 0;
while ((c =fgetc(fp)) != EOF )
{
    if (isdigit(c))
    {
        count++;
        putchar(c);
        if(count == 5)
            break;
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top