How to read in double from a file in C ++

How do you read in a double from a C ++ file?

For ints, I know you can use getline () and then atoi, but I can't find an array for the double function. What is readable in two-local numbers or converting a char array to double?

+2


source to share


4 answers


You can use stream extraction:

std::ifstream ifs(...);
double d;
ifs >> d;

      

This work stipulates that other spaces, the following data in the stream must be double in the textual representation.



Once retrieved, you can check the status of the stream to see if there were any errors:

ifs >> d;
if (!ifs)
{
    // the double extraction failed
}

      

+3


source


Don't consider using atof () or any of the ato .. functions, as they prevent you from diagnosing errors. Take a look at strtod and strtol . Or use stream extraction operators.



+3


source


I'm wondering if I need to be careful about locale settings (eg locale can use comma instead of period to separate decimal part) or do string streams always default to the standard "C locale" notation?

+2


source


You can use istringstream For example, there are double and toInt here:

double toDouble(string s) {
  double r = 0;
  istringstream ss(s);
  ss >> r;
  return r;
}

int toInt(string s) {
  int r=0;
  istringstream ss(s);
  ss >> r;
  return r;
}

      

0


source







All Articles