问题
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