-
user input verification
So, I'm seeing if i can (re)learn programming as a more useful way to spend my time then watch tv.
That said I'm trying to make a card game but I have problem with my input verification function:
Code:
int checknames(char *str,int op) {
/*in progress...*/
int i,j,test,resp=0;
char faces[]="aAkKqQjJtT23456789";
char suits[]="sShHcCdD";
for (i=0;i<strsize(str)-op;i++) {
test=0;
if (i%3 == 0)
for (j=0;faces[j];j++)
if (*(str+i) == faces[j]) {
test=1;
break;
}
if (i%3 == 1)
for (j=0;suits[j];j++)
if (*(str+i) == suits[j]) {
test=1;
break;
}
if (i%3 == 2)
if (*(str+i) == ' ') {
test=1;
break;
}
if (!test) {
resp=1;
break;
}
}
return resp;
}
The idea to verify that the input is in the correct form (that being 'As 5h 6c' for example) and return 1 if the verification fails (the op int is there to tell the function to ignore (or not) the last char of the string and will be either 0 or 1).
So, what I was trying to accomplish was: check if the 1st char is a "face", check if the 2nd char is a "suit", check if there is a ' ' next, repeat until the end of the string (except \0 and sometimes the 1 before), return 1 if it fails or 0 if it passes.
If you could detect what i did wrong (or give any advise in general) i would appreciate it.
-
Umm...try using strchr to check if a face or suit designator is valid, something like
Code:
strchr(faces, str[0]) // returns NULL if str[0] is not in faces
Your valid card is any string that is exactly 2 characters long, with str[0] in faces and str[1] in suits. You could make this a one-line function.
-
So I seemed to have missed the part about the space-separated list of cards. You can split that up into individual cards using something like strtok or sscanf to extract individual cards from the string. You can pass those into the function I described in my previous post. Separating them might not be a bad idea, since you may want to check the validity of an individual card elsewhere in your program too.
-
done
you were right, it is cleaner to separate them with sscanf. thank you