Saving formatted data in C

I am trying to add variables to a C char array. Also I tried sprintf

, but this causes several other problems in my program.

I want to do something like this:

char* age = "My age is = " + age;

      

I am planning to send a char array to a socket using send()

+2


a source to share


3 answers


s (n) printf is indeed the correct answer here. What problems does it cause? Try to fix these problems and discard the correct tool.



+3


a source


If you can use C ++, just use std :: string to get this functionality ...



In section C, you simply cannot do this using operator overloads. "strcat" allows you to combine 2 strange ones. Just make sure you have room to store the resulting string!

+1


a source


Use sprintf()

. Remember to allocate a large enough buffer for the array. Like this:

char buf[24];
sprintf(buf, "My age is = %d", age);

      

24 char

are long enough to contain the result here, regardless of the value age

. I am assuming that age

is a 32 bit integer.

Of course, if you change the text for something longer, you will have to increase the buffer size.

0


a source







All Articles