ctype-conversionstring-conversion

How to convert string to few integers


I have a task. The user has to input 3 numbers in this format (x;y;z).

X, y, and z are 3 integer numbers separated by semicolons. The program gets them like a string and has to convert them to three separate integers.

Input: 22;33;55

Output:

Number1 = 22

Number2 = 33

Number3 = 55

The best way to do this would be with string. Because I have to validate whether the data was input correctly or not.


Solution

  • Simple?

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    int main() {
        char *s = "42;56;97";
    
        if( strspn( s, ";0123456789" ) != strlen( s ) ) {
            fprintf( stderr, "Bad data\n" );
            return 1;
        }
    
        long n1 = strtol(   s, &s, 10 );
        // add check for *s == ';' if you think it appropriate
        long n2 = strtol( ++s, &s, 10 );
        // add check for *s == ';' if you think it appropriate
        long n3 = strtol( ++s, &s, 10 );
        // add check for *s == '\0' if you think it appropriate
    
        printf( "%ld  %ld  %ld\n", n1, n2, n3 );
    
        return 0;
    }
    
    42  56  97