在C ++中将double *转换为std :: string

时间:2014-09-26 11:28:51

标签: c++ string double

我想在C ++中将double*转换为string

#include <iostream>
#include <string>

using namespace std;

int main()
{
  int i;
  double *f = new double[5];

  for(i = 0; i < 5; i++)
  {  
    f[i] = 5;
  }

  string f_str;

  //this is for double to string
  //f_str = std::to_string(f);
  //i want for double*

  cout << f_str << '\n';

  delete [] f;

  return 1;
}

3 个答案:

答案 0 :(得分:2)

尝试使用to_string

   std::stringstream ss;

   for(i = 0; i < 5; i++)
   {  
    f[i] = 5;
    ss << std::to_string(f[i]) << ", ";

   }

   string f_str = ss.str();

答案 1 :(得分:1)

试试这个

#include <iostream>
#include <string>
#include <sstream>

int main( )
{
    const int SIZE(5);
    double *f = new double[SIZE];

    // fill data
    for(int i(0); i < SIZE; i++)
        f[i] = 5;

    std::string doubArray2Str;
    for(int i(0); i < SIZE; ++i){
        std::ostringstream doubleStr;
        if ( i == SIZE - 1 )
          doubleStr << f[i]; 
        else
            doubleStr << f[i] << ","; 

        doubArray2Str += doubleStr.str();
    }
    std::cout << doubArray2Str << std::endl;

    delete [] f;
    return 0;
}

答案 2 :(得分:0)

您可以尝试以下代码。希望这会帮助你的伙伴。感谢。

#include <iostream>
#include <vector>
#include <string>
#include <sstream>

#define MAX 1000

using namespace std;
typedef long long ll;

string DOUBLE_TO_STRING(double data)
{
    string number;

    stringstream out ;
    out << data;
    number = out.str();

    return(number);

}


int main()
{

    ll n;

    while(cin >> n)
    {
        double a[MAX];
        vector<string> str;

        for(ll i=0; i<n; i++){
            cin >> a[i];
            str.push_back(DOUBLE_TO_STRING(a[i]));
        }

        for(ll i=0; i<str.size(); i++)
            cout << str[i] << "\n";
    }


    return 0;
}