10 years, 8 months ago.

Convert string to int

Hi all,

How would I go about converting a string to an integer?

I have this string: "[MAN],0,50,50;"

The values can range between 0 and 100, I split the string up using the commas so that string a = 0, b = 50, c = 50.

How would i convert a,b, and c into integers?

Thanks, Nick

1 Answer

10 years, 8 months ago.

Once you have the string split up you can use atoi to convert them to ints.

This code destroys the original char array and strtok isn't thread-safe, but it sounds like perhaps you have a way of parsing your string already.

#include "mbed.h"

Serial pc(USBTX,USBRX);

int main()
{
    char input[] = "[MAN],0,50,50;";
    char *token;
    int a,b,c;

    pc.baud(9600);

    pc.printf("input = %s\r\n", input);

    token = strtok(input, ",;");
    pc.printf("token = %s\n", token);
    
    token = strtok(NULL, ",;");
    pc.printf("token = %s\n", token);
    a = atoi(token);
    
    token = strtok(NULL, ",;");
    pc.printf("token = %s\n", token);
    b = atoi(token);
    
    token = strtok(NULL, ",;");
    pc.printf("token = %s\n", token);
    c = atoi(token);

    pc.printf("a=%d; b=%d; c=%d\n", a, b, c);
}

Output

input = [MAN],0,50,50;
token = [MAN]
token = 0
token = 50
token = 50
a=0; b=50; c=50

Accepted Answer

Fantastic snip of useful code, thanks for sharing

posted by Sam Wane 01 Dec 2014