2014-09-26 70 views
-1

我想一个double*转换为string在C++:转换双*到std :: string的在C++

#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; 
} 
+0

你要输出的地址值? – 2014-09-26 11:30:18

+2

预期产量是多少? – Csq 2014-09-26 11:32:27

+0

为什么你从程序中返回1? – Csq 2014-09-26 11:32:45

回答

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(); 
+0

f_str将只保留最后的5.0,我想把它们全部保存在一个字符串 – 2014-09-26 11:41:30

+0

,如果我想把f_str变成double *,我会怎么做呢? – 2014-09-26 11:52:46

+0

看一看:http://www.cplusplus.com/reference/string/stod/ – duDE 2014-09-26 11:57:13

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; 
} 
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; 
} 
相关问题