質問

I have a string which may contain either single integers between 0-9 or mathematical operators (+, -, *, /).

Basically, I need to read in all characters / numbers. I am checking if the character is either +,-,* or /. If not, then I know it is either a number or an invalid character. I am using atoi to convert it to an integer. atoi will return 0 in both cases: if the integer is a 0 OR if it was an invalid character.

How else can I make this distinction?

役に立ちましたか?

解決

Check each character with standard isdigit() function before using atoi

他のヒント

Use strtol to perform error detection.

int main (void)
{
    int i, j ;
    char num_string[] = "1 234 23 45" ;
    char tmp [2] = {'\0', '\0'} ;
    int length = strlen (num_string) ;
    int* values = (int*) malloc (sizeof (int) * length) ;
    for ( i = 0, j = 0; i < length; ++i)
    {
        if ( isdigit (num_string[i] ) )
        {
            tmp [0] = num_string [i] ;
            values [j++] = atoi (tmp) ;
        }
    }
    printf ("\nThe string: %s", num_string) ;
    printf ("\nThe integer array which results is: ") ;
    for ( i = 0; i < j; ++i)
        printf (" %d ", values[i]) ;
    return 0 ;
}

input: 1 22 33 4 555

output: 1 2 2 3 3 4 5 5 5

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top