Help with a function to check for doubles

closed account (35S3T05o)

I cannot figure out why the program continues to prompt me for a vaild number even when the correct number( a gpa) is entered. I'm not sure if the problem lies in the isDouble function or the getDouble?


1
2
3
4
5
6
7
8
9
10
11
12
13
* Determines whether the string holds a valid double. Checks if each 
 *    character is digit and there is no more than 1 decimal point.
 */
bool isDouble (const string &str) {
	int decimal = 0;
	for (unsigned int i = 0; i < str.size(); ++i){
		if ( str[i] == '.'){
			decimal++;}
		if( !isdigit(str[i]) && (str[i] != '.')) return false;
	}
	if( (decimal != 1) || (!isInteger(str))) return false;
	return true;
}


1
2
3
4
5
6
7
8
9
10
11
double getDouble (const string &msg) {
	cout << msg;
	string num;
	cin >> num;
	while( !isDouble(num)){
		cout << "Enter a valid number ";
		cin>> num;
	}
	double s = atof(num.c_str());
	return s; // stubbed method. Replace this return statement.
}
I would propose this instead:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
bool isDouble (const std::string &str)
{
    int decimal = 0;

    for (unsigned int i = 0; i < str.size(); ++i)
    {
        switch (str[i])
        {
            case '.': ++decimal;
            case '0':
            case '1':
            case '2':
            case '3':
            case '4':
            case '5':
            case '6':
            case '7':
            case '8':
            case '9':
                continue;
            default:
                return false;
        }
    }
    if(decimal != 1)
        return false;
    return true;
}


Works for me.
Topic archived. No new replies allowed.