Convert subsections of array of char to int

Viewed 75

Is there a strtol() or sscanf() equivalent where you can specify the no. of chars to convert?

I have a use case where I need to convert sub sections of an array of chars to ints, so I don't have the terminating null char present

In other words, I'd like the equivalent of strncmp() in relation to strcmp()

i.e. strntol() or snscanf() but they don't seem to exist

I imagine i'll just have to copy and append a '\0' and use strtol() or sscanf() but just wanted to check I hadn't missed an existing function for this purpose

question is really do they exist? am i just searching for the wrong thing?

1 Answers

There is no equivalent for strtol, but you can use format specifier to limit the number of characters considered by sscanf:

char *str = "1234567890";
int n;
sscanf(&str[3], "%3d", &n);
printf("%d\n", n);

The %3d specifier instructs sscanf to take only three digits from str, while &str[3] tells sscanf to start at the index 3.

The above code prints 456 (demo).

Related