validating a string variable

I would like to make a simple function that accepts a string variable and tests it to see if it's in the form of ( number/number ) so that I can use it in a fraction class, but I'm having trouble with the function. when I type h/5, it just displays it on the screen, it want prompt me to re-enter the string or anything, any ideas where I'm messing up at?
- thanks for any help-

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
#include <iostream>
#include <string>
using namespace std;
bool validate(string s);
int main()
{
	string fraction;
	cout << "enter fraction string\n";
	cin >> fraction;

	while (validate(fraction) == false)
	{
		cout << "enter new fraction\n";
		cin >> fraction;
	}
	cout << fraction;
}
bool validate(string s)
{
	for (int i = 0; i < s.size(); i++)
	{
		if (isalpha(s[i]) == true)
		{
			return false;
		}
		if (isspace(s[i]) == true)
		{
			return false;
		}
		if (ispunct(s[i]) == true)
		{
			if (s[i] != '/')
			{
				return false;
			}
		}
	}
	return true;
}
The return type of isalpha, isspace and ispunct is int. Instead of returning false these functions return 0, and instead of true a non-zero value is returned.

When a bool is compared to an int the bool is first converted to an int, false becomes 0 and true becomes 1. Line 22 is the equivalent to writing if (isalpha(s[i]) == 1). The problem is that isalpha not guaranteed to return 1 when the character is an alphabetic character. It could return any non-zero value so the condition might never be true.

You could change the line to something like if (isalpha(s[i]) != 0) but that is not necessary. In if statements and anywhere a bool is expected an int value of 0 is considered false and anything else is considered true so you can use the return value of isalpha and the other functions directly in the if condition without using the == operator.
 
if (isalpha(s[i]))
I didn't realize that, thanks alot!
Topic archived. No new replies allowed.