Anidh Singh
Anidh Singh

Reputation: 324

How to check whether a variable is of integer type

I simply want to check whether a value which is present in a variable is integer or not.

My program below reads two values from "myfile.txt" and performs addition if and only if they are integers otherwise it returns "Invalid Output". I have successfully read values from "myfile.txt" but i have no way of checking whether the two values are integer or not.How to perform this test?

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

int main()
{
    FILE *fp;
    int i, mkji, num, num1, num2;
    int s = 0;
    int a[2];
    char term, term2;
    clrscr();
    fp = fopen("myfile.txt", "r+");
    if (fp != 0)
    {
        for(i = 0; i < 2; i++)
        {
            fscanf(fp, "%d", &a[i]);
        }
        for(i = 0; i < 2; i++)
        {
            printf("%d\n", a[i]);
        }
        num = a[0];
        num1 = a[1];
        num2 = num + num1;
        printf("%d", num2);
        mkji = fclose(fp);
    }
    else
        printf("FILE CANNOT BE OPEN");
    getch();
    return 0;
}

Upvotes: 1

Views: 209

Answers (3)

Danyal Imran
Danyal Imran

Reputation: 77

check the return value from fscanf()

it can return -1 for a non number
and 0 or 1 for a number.

Upvotes: 0

Martin Gardener
Martin Gardener

Reputation: 1001

Read the file as ASCII character and check for their ASCII Codes. If the ASCII lies in the range of a number 0 number has ASCII 48 and 9 number has ASCII 57. so each number lies between ASCII 48 to 57.

you can concatenate them in a string since you are reading characters until a space appears and once you get 2 numbers just add them :)

code can be in the form of

char[] number1;
char numRead;
keep reading the number using fscanf until a non-number appears.
if ( numRead >= '0' && num <= '9' ) // checking for if it is a number.
   number1 += numRead; // atleast thats how you do it in C++

Upvotes: 0

fuz
fuz

Reputation: 93127

Check the return value of fscanf. fscanf returns the number of succesfully scanned items or -1 if there was an IO error. Thus, if the number was malformed, fscanf("%d",&a[i]); should return 0.

Upvotes: 1

Related Questions