check if string is certain numbers
Sorry about the crappy title but i couldnt think of what to call it.
anyway,
you may have seen my other post, if not, heres what I'm doing...
I am making a 4d tic tac toe game. i cin the coordinates as a string then change it to an int array (trouble with this step is the topic of my other post).
what i need to do now is check that the number entered is valid.
to be valid, it must be a 4 digit number in which all 4 digits are a 0, 1, or 2.
examples of good: 0020, 1212, 2001, 1220, etc.
examples of bad: 4123, h732, 23411, 4, hffr, etc.
does anyone have any suggestions?
(i've just finished my 1st c++ class so im not THAT good at this so anything you can do is apreciated, if you suggest anything thats "advanced" I would appreciate a code sample or a link that I can go to to figure out how to do it.)
Thanks,
Nick
[902 byte] By [
nick53182] at [2007-11-11 7:32:26]

# 2 Re: check if string is certain numbers
Hi,
try something like:
(obviously you should put ths in some sort of function and pass cellValue as a parameter)
char cellValue[4];
cellValue[0] = '1';
cellValue[1] = '1';
cellValue[2] = '1';
cellValue[3] = '1'; // cellValue=="1111", will return isValid = true
bool isValid = true;
for(int i=0;i<4;i++)
{
if(cellValue[i] < '0' && cellValue[i] > '9')
{
isValid = false;
}
}
if(isValid)
{
cout << "Hooray!!!" << endl;
}
This will set the value of isValid to the boolean value false when any of the char's in the char array 'cellValue' is not a number.
Cheers,
D
# 3 Re: check if string is certain numbers
bool isValid(int num) {
/** it can't be valid if it is not in this range */
if (!(num >= 0 && num <= 2222)) {
return false;
}
stringstream ss;
ss << num;
string cellValue = ss.str();
/** loop through each character */
for (int i = 0; i < 4; i++) {
if (cellValue[i] != '0' && cellValue[i] != '1' && cellValue[i] != '2') {
return false;
}
}
return true;
}
This should work... i haven't compiled it though..
destin at 2007-11-11 21:04:07 >
