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

断了今生、忘了曾经 提交于 2019-12-11 02:49:34

问题


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 function. What is available for reading in doubles, or converting a char array to a double?


回答1:


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
}



回答2:


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.




回答3:


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?




回答4:


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;
}


来源:https://stackoverflow.com/questions/2615078/how-to-read-in-a-double-from-a-file-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!