Parse double

I'm currently trying to convert a string to a double. Right now all I'm doing is:
1
2
double f;
cin >> f;


which is great... if the user enters in a double. If the user doesn't then the program doesn't execute correctly. My question is how would I parse the double correctly? I know in Python you'd use exception handling and in vb.net/c# you'd using Double.TryParse, but I'm not sure about c++. Any help is appreciated.
If you error check with a string then you will have to use a stringstream and stream it into a double. http://www.cplusplus.com/reference/sstream/stringstream/?kw=stringstream using the operator

Another method would be to ignore and clear the buffer if the user enters something other than a double.
http://www.cplusplus.com/reference/ios/ios/ (under flags)
http://www.cplusplus.com/reference/istream/istream/ignore/?kw=cin.ignore
I found a pretty sweet example online after searching stringstream and this is what I came up with:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
double get_input(string input)
{
	double converted;
	stringstream ss(input);

	//If it can't be converted...
	if ( !(ss >> converted) )
	{
		//Return a null or 0 value
		converted = 0;
	}

	return converted;
}


Which works excellently.
Topic archived. No new replies allowed.