String Problem Question

Hello, I am taking a C++ course and was given this problem to work out:

Write and test a C++ function named isvalidReal() that checks for a valid double
precision number. This kind of number can have an optional + or – sign, at most one decimal point, which can be the first character, and at least one digit between 0 and 9 inclusive.
The function should return a Boolean value of true if the entered number is a real
number, otherwise, it should return a Boolean value of false.

The reason I'm stuck is the fact that I don't know how to run through the user inputted string and search for any non-integers or additional instances of a decimal point. I'm probably just overlooking a basic command that can do this but I cannot figure it out. I would appreciate any help.
C strings are arrays of chars, meaning you can traverse each element (char) of the string in the same way you do other arrays. You can also use the isdigit() function to test whether a char is a digit.
Thanks Jose! I got somewhere with that isdigit() command.. however now I am getting a Debug Assertion Failed message that says the "string subscript is out of range" whenever I enter a real integer, it seems to work correctly if I insert another character though. Here's what my code looks like:

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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52

#include <iostream>
#include <cmath>
#include <string>


using namespace std;

int isvalidReal(string);


int main()
{
	string A;
	bool TOF;
	
	cout<<"Please type in any real number with an optional +/- sign in front: ";
	cin>>A;
	TOF= isvalidReal(A);
	if(TOF==1)
		cout<<"The number is a real number"<<endl;
	else
		cout<<"The number is not a real number"<<endl;
	system("pause");
	return 0;
}

int isvalidReal(string a){

	bool tof; int i= 0, j= 1; string str="+-.";

	for(i= 0; i<=a.length(); i++){
	
	if(isdigit(a[i])){
		tof= 1;
	}
	else if(a[0]==(str[0]||str[1]) && a[1]==isdigit(a[1])){
		tof= 1;
	}
	else if((a[i]==str[2]) && j==1){
		tof= 1;
		j= 0;
	}
	else {
		tof= 0;
		break;
	}

	}

	return tof;
}
closed account (DSLq5Di1)

for(i= 0; i<=a.length(); i++){

Going out of bounds here on the last iteration, change to "i < a.length()".
I got it working, thank you!
Topic archived. No new replies allowed.