C question - programming?

2009-03-17 4:10 am
C question - programming?
Is there a function to check if a string is a positive integer in C?

I have tried someone's idea using atoi(), but I found a problem.
Because atoi would return a value that is not zero, even if the string contains some characters in it. E.g. 27abc

atoi would return 27. I just want the function to check if the string is a positive integer with nothing else attached with it. How can I do that? thank you.

回答 (2)

2009-03-17 1:57 pm
✔ 最佳答案
I think you're looking for something like this:

#include <stdio.h>

#define MAX_LINE_LEN 256

typedef enum { false = 0, true } bool;
unsigned getUnsigned();

int main(int argc, char *argv[]) {
    while (1) {
        printf("> ");
        printf("%u\n",getUnsigned());
    }
    return 0;
}

unsigned getUnsigned() {
    bool inputOk;
    char line[MAX_LINE_LEN];
    char junk[MAX_LINE_LEN];
    int z;

    for (inputOk = false; inputOk == false; ) {
        fgets(line,MAX_LINE_LEN,stdin);
        inputOk = ((sscanf(line,"%d%s",&z,junk) == 1) &&
                              (z > 0));
        if (inputOk == false) {
            printf("invalid input, try again: ");
        }
    }
    return z;
}

#if 0

Sample run:

> 99
99
> x
invalid input, try again: 27abc
invalid input, try again: -10
invalid input, try again: 10
10
> 1
1
> 0
invalid input, try again: 10 20
invalid input, try again: 100
100
>

#endif
2009-03-17 11:45 am
Best way I can think of is to test each character one at a time and make sure it falls within the ASCII range for numbers 0-9 (48-57)

char num[]; //contains 12345
int x = 0;
while (word[x] != '\0') { // While the string isn't at the end...
if(word[x] >= 48 && word[x] <= 57) {
cout << word[x]; // Output the valid positive number
}
x++;
}

You can make allowances for a '+' sign as the first character if you wish (ASCII value 43), or disallowing a negative sign (ASCII value 45).


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

檢視 Wayback Machine 備份