In my program, i need to verify that the parameter passed to the program is an integer, so i created this little function to handle the case where user typed "1st" instead of "1".
The problem is that it doesn't work at all. I try the debug and all i can tell you is that the parameters are 12 and the long is 2. (12 is the value i want to test, and 2 is the number of the numbers passed to the function)
int intOnly(char *toCheck, int longeur) {
int i = 0;
while (i < longeur) {
开发者_开发问答 switch (toCheck[i]) {
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
case 9:
case ' ':
i++;
default:
return 0;
break;
}
return 1;
}
}
I hope that everything is clear, Thanks for you help ;)
If you want to check if a character is one of the ten digits, you need to use the character constants '0'
, '1'
, etc. (not integer constants, 0
, 1
, etc.).
Once you've fixed the problems that have already been pointed out, you should probably look up isdigit
and isspace
and use them to write the function much more cleanly. Another possibility would be to use something like strcspn
or strpbrk
to do the search in a single step.
Just use strtol
this will convert the integer and you can tell from the third param if it succeeded.
For description see strtol(3)
Firstly, I'm surprised that your code gets past compiling, with a variable named long. However, your real issue is that you're using the numbers 0-9, rather than the characters '0'
through '9'
in your switch.
In addition to the other answers, consider using isdigit
instead. Also consider renaming your function to reflect what it really does (such as intsAndSpacesOnly
)
You can use the isdigit
and isspace
function as:
int intOnly(char *toCheck, int len) { // long is reserved word..use len.
int i = 0;
while (i < len) {
if(!isdigit(toCheck[i]) && !isspace(toCheck[i]))
return 0;
i++;
}
return 1;
}
Also long is a keyword which you cannot use as an identifier.
You could make your life easier and your code shorter if you use ctype.h, specifically the isdigit or
if(toCheck[i] >= '0' && toCheck[i] <= '9' || toCheck[i] == ' '){
I'm assuming you mean a positive integer, as your code will fail if negative numbers are passed in, similarly if exponents are passed in (e.g., 1000 as 1e3). The latter is probably rare you'd need to worry about, but the former may be something to think about - I don't know for what purpose you're validating, but just a heads-up :-)
You may want to add a break;
statement after the i++;
statement. Otherwise, you will always 'fall' through the default
branch and return a 0.
UPDATE: [this is an old question, but for the sake of completeness]
In addition to the missing break
statement, it is also not cleat how you treat the case where the user enters a string containing a space between digits: 123 456
. Your function identifies this as an integer, but I think this should flag an error.
精彩评论