开发者

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

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

For ints I know you can use the getline() and then atoi, but I am not finding an array to double 开发者_StackOverflow社区function. What is available for reading in doubles, or converting a char array to a double?


You can use stream extraction:

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

This work provided that other then whitespace, the next data in the stream should be a double in textual representation.

After the extraction, you can check the state of the stream to see if there were errors:

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


Do not consider using atof(), or any of the ato.. functions, as they do not allow you to diagnose errors. Take a look at strtod and strtol. Or use the stream extraction operators.


I'm wondering, does one need to be careful about locale settings (e.g. a locale could use comma instead of dot to separate the decimal part) or do stringstreams always default to some standard "C locale" notation?


You can leverage istringstream For example, here are toDouble and toInt:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜