Home > front end >  How can I verify if a file only contains numbers in C?
How can I verify if a file only contains numbers in C?

Time:11-25

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.

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?

CodePudding user response:

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

CodePudding user response:

int is_number(char *str)
{
    int i = 0;
    while (str[i] != '\0')
    {
        if (str[i] < '0' || str[i] > '9')
            return 0;
        i  ;
    }
    return 1;
}

maybe this. so you are looking if variable only has numbers?

CodePudding user response:

ok maybe this works better

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

int main()
{
    FILE *fp;
    char c;
    char s[100];
    int i = 0;

    fp = fopen("test.txt", "r");
    if(fp == NULL)
    {
        printf("Error opening file");
        exit(1);
    }

    while((c = fgetc(fp)) != EOF)
    {
        if(isdigit(c) == 0)
        {
            printf("Not only integers\n");
            break;
        }
    }

    if(c == EOF)
        printf("Only integers\n");

    fclose(fp);

    return 0;
}

but yeah its pretty much same thing

  •  Tags:  
  • c
  • Related