Kurbamit
Kurbamit

Reputation: 105

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.

Upvotes: 0

Views: 70

Answers (2)

Fe2O3
Fe2O3

Reputation: 8354

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

Upvotes: 1

user9706
user9706

Reputation:

Here is the implementation of @MarcoBonelli's idea:

#include <stdio.h>

int main(void) {
    int number[3];
    sscanf("22;33;55", "%d;%d;%d", number, number + 1, number + 2);
    printf("number 1: %d, number 2: %d, number 3: %d\n", number[0], number[1], number[2]);
}

and the output:

number 1: 22, number 2: 33, number 3: 55

If you want to write a parser it's way more verbose but generic and easily extendable (in this case parsing the gramma: l(;l)* where l is a long and ; your separator). It also illustrates how to use strtol():

#include <errno.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>

const char *parse_ch(const char *s, char ch) {
    if(!s || *s != ch)
        return NULL;
    return s+1;
}

const char *parse_long(const char *s, long *l) {
    if(!s)
        return NULL;
    char *endptr;
    *l = strtol(s, &endptr, 10);
    if((*l == LONG_MIN || *l == LONG_MAX) && errno == ERANGE)
        return NULL;
    return endptr;
}

int main(void) {
    const char *s = "22;33;55";
    long l;
    s = parse_long(s, &l);
    if(!s) return 1;
    printf("number: %ld\n", l);
    for(;;) {
        s = parse_ch(s, ';');
        if(!s) return 0;
        s = parse_long(s, &l);
        if(!s) return 1;
        printf("number: %ld\n", l);
    }
}

Upvotes: 1

Related Questions