Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting int[] to String in C++

I have a string defined as std::string header = "00110033"; now I need the string to hold the byte values of the digits as if its constructed like this

char data_bytes[] = { 0, 0, 1, 1, 0, 0, 3, 3};
std::string header = new std::string(data_bytes, 8).c_str());

I converted the initial string to int array using atoi. Now i'm not sure how to make the string out of it. Let me know if there is any better approach.

like image 283
Manoj Avatar asked Mar 07 '11 17:03

Manoj


People also ask

Can I convert int to string in C?

itoa() Function to Convert an Integer to a String in C itoa() is a type casting function in C. This function converts an integer to a null-terminated string. It can also convert a negative number.

What is Strtol () in C?

In the C Programming Language, the strtol function converts a string to a long integer. The strtol function skips all white-space characters at the beginning of the string, converts the subsequent characters as part of the number, and then stops when it encounters the first character that isn't a number.

What does itoa mean in C?

C Programming/stdlib. h/itoa The itoa (integer to ASCII) function is a widespread non-standard extension to the standard C programming language. It cannot be portably used, as it is not defined in any of the C language standards; however, compilers often provide it through the header <stdlib.


1 Answers

you could write a little function

string int_array_to_string(int int_array[], int size_of_array) {
  string returnstring = "";
  for (int temp = 0; temp < size_of_array; temp++)
    returnstring += itoa(int_array[temp]);
  return returnstring;
}

untested!

a slightly different approach

string int_array_to_string(int int_array[], int size_of_array) {
  ostringstream oss("");
  for (int temp = 0; temp < size_of_array; temp++)
    oss << int_array[temp];
  return oss.str();
}
like image 197
ultifinitus Avatar answered Sep 30 '22 10:09

ultifinitus