Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I verify if a file only contains numbers in C?

I’m a beginner in learning C. If I have a file with the given format:

12 20 40 60 80
04 10 34 30 20

How can I verify with a function that it’s integers only.

I’m working on an assignment that requires me to do this. That is why I can’t include my main but I am passing a file into my function.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

bool check(FILE *fp) {
    int numArray[26];
    int i = 0;
    int num;
    while(fscanf(fp, "%d", &num)) {
        if (isdigit(num) == 0) {
            fprintf(stderr, "Not correct format ");
            return false;
        } else 
        {
            numArray[i] = num;
            i++;
        }
    }
}

If I give it the incorrect format such as

12x 10 15 13 10

Nothing happens. I was wondering if anyone can point me in the right direction?

>Solution :

fscanf will return the number of successfully recognized patterns from the format in the input; if it sees something that does not match the next format pattern (such as a letter for a %d pattern) it will reject it and return a smaller number. So in your case, you can just look for fscanf returning 0:

bool check(FILE *fp) {
    int numArray[26];
    int i = 0;
    int num;
    int matched;
    while ((matched = fscanf(fp, "%d", &num)) != EOF) {
        if (matched == 0) {
            fprintf(stderr, "Not correct format\n");
            return false;
        } else if (i >= 26) {
            fprintf(stderr, "Too many numbers\n");
            return false;
        } else 
        {
            numArray[i] = num;
            i++;
        }
    }
    return true;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading