Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   I am facing a problem please help me ! (http://www.go4expert.com/forums/i-facing-help-t19011/)

sujan.dasmahapatra 12Aug2009 20:55

I am facing a problem please help me !
Dear Friends
I am reading an int and a double from file.
How can I check whetheer the value read is an int or double.

int intval;
double doubleval;
ifstream infile("Data.dat")
infile >> intval >> doubleval;
// how can I check whether intval has got an integer and doubleval has got a double value.
//infile.dat has
2 23.323
what happens if infile.dat has data like this
# &&*********
//so it'll read junk values so how could I check the variables.??
Please help me to overcome this problem!!!

VatooVatoo 13Aug2009 16:54

Re: I am facing a problem please help me !
if file's data is not what you expected as you shown, you will receive int and double data with unexpected values

I mean all things in computer memory are numbers, also characters indicate numbers in memory. so you will receive a number equal to that byte(s) pointed in file.

xpi0t0s 13Aug2009 22:10

Re: I am facing a problem please help me !
You can't really, because you're using internal functions to do the conversion, so you would need to use functions that throw errors if the data is not expected, or parse the data yourself.

So one way to do this is to read the contents of the file into a string variable, then scan the string looking for valid digits and adding them to the number, e.g. (untested)

char *str="23.323"; // imagine we've just read this in from the file
float decmask=0.1;
int dec=0; // doing the bit after the dot
float total=0.0;
for (int i=0; str[i]; i++)
  if (str[i]>='0' && str[i]<='9')
    if (dec)
      total += decmask*(str[i]-'0');
    else total=total*10+str[i]-'0';
  else if (str[i]=='.')

This is just basic string to float conversion and you would need to add some error checking to this if you want it to pick out problematic input such as 23.3'23, or 12.34.56.
Also you might want to add range checks, so if after adding a new digit total is less than the previous result or negative, then you've just overflowed; similarly if at any point decmask becomes zero then you're unable to represent the precision in the file, and the design will determine how you need to handle that situation.

All times are GMT +5.5. The time now is 14:14.