C question - programming?

2009-03-17 3:37 am
Is there a function to check if a string is a positive integer in C?

回答 (2)

2009-03-17 4:11 am
✔ 最佳答案
You can actually do this check very fast as long as you don't care if it is a number with a decimal point (not an integer, but still a positive number):

char * your_string = (something);

if (isdigit(*your_string)) {
return true;
} else {
return false;
}

This only finds strings that actually start with a number -- if you had something like " 15" it would not work and you would have to advance the pointer past the whitespace first. Still, that gives you the basic idea.

isdigit is in the ctype library -- you will need to type #include <ctype.h> at the top of your code.
2009-03-17 10:52 am
By nature, strings are not integers, but an array of characters.

If you mean the contents of the string is numerically a number, and you want to see if it's positive or not, then you can do something like this:

char * your_str;
int your_int;

your_int = atoi(your_str);

if (your_int > 0)
printf("The string is positive.\n");
else
printf("The string is not positive.\n");


If that's not what you mean, you'll have to clarify.


收錄日期: 2021-05-01 12:08:51
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20090316193717AAroVEs

檢視 Wayback Machine 備份