Converting int[] to String in C++

2020-02-09 17:50发布

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.

6条回答
Viruses.
2楼-- · 2020-02-09 17:59

You can do this:

std::string header( data_bytes, data_bytes + sizeof( data_bytes ) );
std::transform( header.begin(), header.end(), header.begin(), 
     std::bind1st( std::plus< char >(), '0' ) );
查看更多
▲ chillily
3楼-- · 2020-02-09 18:03

Assuming you're using a "fairly normal" system where the numeric values of '0' to '9' are consecutive, you can just iterate over each element and subtract '0':

for(int i = 0; i < header.size(); ++i)
{
    header[i] -= '0';
}
查看更多
Deceive 欺骗
4楼-- · 2020-02-09 18:06
 char data_bytes[] = { 0, 0, 1, 1, 0, 0, 3, 3};
  std::string str;
 for(int i =0;i<sizeof(data_bytes);++i)
      str.push_back('0'+data_bytes[i]);
查看更多
相关推荐>>
5楼-- · 2020-02-09 18:06

If integ[] is the integer array, and s is the final string we wish to obtain,

string s="";

for(auto i=0;i<integ.size()-1; ++i)
    s += to_string(ans[i]); 

cout<<s<<endl;
查看更多
三岁会撩人
6楼-- · 2020-02-09 18:24

Do this:

  char data_bytes[] = { '0', '0', '1', '1', '0', '0', '3', '3', '\0'};
  std::string header(data_bytes, 8);

Or maybe, you want to do this:

  std::stringstream s;
  s << data_bytes;
  std::string header = s.str();

Demo at ideone : http://ideone.com/RzrYY


EDIT:

Last \0 in data_bytes is necessary. Also see this interesting output here: http://ideone.com/aYtlL

PS: I didn't know this before, thanks to Ashot I came to know this difference by experimenting!

查看更多
Luminary・发光体
7楼-- · 2020-02-09 18:25

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();
}
查看更多
登录 后发表回答