Reputation: 480
My fscanf function is supposed to be getting 3 numbers from the file and storing them in charr arrays which I then turn into ints and floats using atoi and atof.
How would I go about checking whether:
In the second case, I was thinking that just testing whether the conversion of the string to int/float was sucessfull would be enough
if(atoi(numberchar) == 0){printf("sorry error");}
However, zero is a valid value for my numbers(both floats and ints) so here I am running into a problem.
I have also noticed that with input 45kl for example, the atoi/atof functions convert this to 45. So the only thing to look out for here is when the input does not start with digits?
For this I could just write a condition that if the first element of the array is not zero but the atoi/atof function failed anyways (returning zero) then the input probably had a non digit character at the beginning.
Is that right?
Upvotes: 0
Views: 1293
Reputation: 3454
The man page of scanf family function (man scanf) clearly states that the return value is the number of input elements assigned.
If the returned number is greater than zero then it equals the number of elements read according to the specified conversion. If the number is 0 then, even if there were elements to read, no one would be assigned if they do not match the conversions, as in the case when you specify %d but then, a letter is encountered while reading. EOF is returned in case of input failure such as the end of the file.
So, fscanf does all the job you want, you just have to check the number of items returned. If you are expecting 3 integer, fscanf will return 3 if and only if it reads 3 integer values.
Generally speaking, to check for a number, i suggest the use of the function isdigit().
Upvotes: 4
Reputation: 21965
I am not sure if this code is foolproof but it is just a try :
#include<stdio.h>
int main()
{
FILE *fp;
int a,b,c;
char d;
if ((fp=fopen("touchscanf","r")) == NULL)
{
printf("Sorry! Can't open the file");
}
else
{
while(4 == fscanf(fp,"%d %d %d%c",&a,&b,&c,&d))
{
if(d!='\n')
{ break;}
printf("Intigers scanned are %d %d %d\n",a,b,c);
}
if(!feof(fp))
printf("Input mismatch\n");
}
fclose(fp);
}
As per this link
The fscanf function returns the value of the macro EOF if an input failure occurs before the first conversion (if any) has completed.
This means that for the below input :
4 20 23
52 65 er
96 96 82
you will get :
Intigers scanned are 4 20 23
Input mismatch
& for
4 20 23
52 65 96
er 96 82
you will get :
Intigers scanned are 4 20 23
Intigers scanned are 52 65 96
Input mismatch
So :
that it was really a number and not something like 7jho or ad841
is answered.
The additional variable d
is to prevent wrapping around to take input. So the input
4 20 23
65 96
96 96 82
will give you :
Intigers scanned are 4 20 23
Input mismatch
The variable d
in a sense enforces a strict input at the cost of a byte space.
So
it really got all 3 of them and not just 2 for example
is answered.
Upvotes: 1