How can I check if a number (double type) stored as a string is a valid double number in C++?
c++, types
Solution
use strtod, which converts a string to a double and returns any characters it couldn't interpret as part of the double.
double strtod(const char* nptr, char** endptr)
Like this:
char* input = "3.1456.365.12";
char* end;
strtod(input, &end);
if (*input == '\0')
{
printf("fail due to empty string\n");
}
if (end == input || *end != '\0')
{
printf("fail - the following characters are not part of a double\n%s\n", end);
}
Problem
I'm having an issue with a program I'm working on in C++. I am asking the user to input a valid number. I take it in as a string because the particular assignment I'm doing, it makes it easier in the long run. For basic error checking, I want to check to see if the number entered is a valid number. Example: ``` Enter number: 3.14 This would be valid Enter number: 3.1456.365.12 This shouldn't be valid ```