1. We have moved from vBulletin to XenForo and you are viewing the site in the middle of the move. Though the functional aspect of everything is working fine, we are still working on other changes including the new design on Xenforo.
    Dismiss Notice

I am facing a problem please help me !

Discussion in 'C' started by sujan.dasmahapatra, Aug 12, 2009.

  1. sujan.dasmahapatra

    sujan.dasmahapatra New Member

    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!!!
     
  2. VatooVatoo

    VatooVatoo New Member

    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.
     
  3. xpi0t0s

    xpi0t0s Mentor

    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)
    Code:
    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');
          decmask/=10;
        }
        else total=total*10+str[i]-'0';
      }
      else if (str[i]=='.')
      {
        dec=1;
      }
    }
    
    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.
     

Share This Page