[RobotC] Concatenate an int to a string

How do I concatenate an int to a string? The code:


string str = "";
int n=5;
str+=n;

Gives me:


**Error**:Cannot concatenate a number to a string.

Is there I way I can cast n to a string? Is there some function that I can append the int to the string?

Use sprintf. Dets.


int intyIntIntInt = 42;
string stringy;
sprintf(stringy, "Stringy string string string %d", intyIntIntInt);

In C the ‘+’ operator does not concatenate, that’s a Java/PHP/JS thing.

sprintf works just like printf, which takes in a string with formatting special characters and then a variadic amount of arguments which are filled in.

ALTERNATIVELY:

Use atoi. Dets.

int intyIntIntInt = 42;
strcat("Stringy string string string ", atoi(intyIntIntInt));

I’m not 100% sure how ROBOTC allocates strings, in the raw world of C they would be char arrays and need to be allocated to a certain size beforehand.

Thanks! Sprintf worked. I didn’t try atoi.

The atoi function will not do what you want. It takes a string and returns an integer. (It stands for “ASCII to integer.”)

I meant itoa, but I use atoi like all the time. Brain being stupid lol, good catch.