Very new to c++ but I can't wrap my head around this

I get this array of doubles and just want to make it to a 'string' with spaces inbetween

In java I would just iterate over all entries and StringBuilder.append(arr[i]).append(' ');

I don't know how to do this in c++ , best thing I came up with was this

wchar_t* getStuff(const double *arr, const int arr_size)
{
  std::vector<wchar_t> result(arr_size*2);

  for( int i = 0; i < arr_size*2; i++)
  {
    if ( i % 2 == 0 )
        result[i] = ?;
    else
        result[i] = L' ';
  }

  return &result[0];
}

I know this does not compile and contains some non-c code.

I am bit lost here since I don't know a good way to convert and what exactly here is a pointer and which is a real value.

有帮助吗?

解决方案

You can use a std::wostringstream to achieve this.

wchar_t* getStuff(const double *arr, const int arr_size)
{
  std::vector<wchar_t> result(arr_size*2);

  for( int i = 0; i < arr_size*2; i++)
  {
    std::wostringstream theStringRepresentation;
    theStringRepresentation << arr[i];
    // use theStringRepresentation.str() in the following code to refer to the 
    // widechar string representation of the double value from arr[i]
  }

  return &result[0];
}

Also note that returning a local scope variable reference is undefined behavior!

return &result[0]; // Don't do this!

Why not simply using a std::vector<std::wstring> instead of the std::vector<wchar_t>?

std::wstring getStuff(const double *arr, const int arr_size) {
  std::vector<std::wstring> result(arr_size*2);

  for( int i = 0; i < arr_size*2; i++)
  {
    std::wostringstream theStringRepresentation;
    theStringRepresentation << arr[i];
    // use theStringRepresentation.str() in the following code to refer to the 
    // widechar string representation of the double value from arr[i]
  }

  return result[0];
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top