2017-07-02 149 views
-2

我已經寫了代碼來存儲二維數組中的值,如下格式,它工作正常。C++初始化和填充變量的二維數組

//Create array 
double MyPoints[25][3] = {{4,3,1},{6,4,1},{7,3,1},{7,6,1},{6,7.5,1},{3,6,1},{4,5,2},{5,6.5,2},{6,9,2},{3.5,8,2},{6,5,3},{6,6,3},{9,4,3},{9,5,3},{8,4,4},{9.5,3,4},{10,4,4},{11,6,4},{9,6,4},{8,7,5},{10,7,5},{11,9,5},{8,10,5}} ; 
cout << "Array Filled" << endl; 

// Print Array 
    for (int c = 0; c < 25; c++) 
    { 
     for (int d = 0; d < 3; d++) 
     { 
      cout << MyPoints [c][d] << " Hellow "; 
     } 
     cout << endl; 
    } 

,但我想數組值存儲在變量,然後分配變量(內舉行陣列值),以填補MyPoints陣列,這是行不通的!。

String MyVar = {{4,3,1},{6,4,1},{7,3,1},{7,6,1},{6,7.5,1},{3,6,1},{4,5,2},{5,6.5,2},{6,9,2},{3.5,8,2},{6,5,3},{6,6,3},{9,4,3},{9,5,3},{8,4,4},{9.5,3,4},{10,4,4},{11,6,4},{9,6,4},{8,7,5},{10,7,5},{11,9,5},{8,10,5}} ; 

double MyPoints [25][3] = MyVar ; 
cout << "Array Filled" << endl; 

我做錯了什麼?如何糾正它。

+1

沒有標準C++中的'String'類型。你能否澄清你想要達到的目標?請參考[tour](https://stackoverflow.com/tour)並閱讀[幫助頁面](https://stackoverflow.com/help)。 – Ron

+1

爲什麼你想要一個單獨的變量?支撐初始值設定項列表沒有類型,所以這個工作的唯一方法就是如果'MyVar'是一個二維數組,但不需要'MyPoints'了... – Rakete1111

+0

我需要MyVar,導致文本並非如我所寫的那樣是靜態的,但是本文「{{4,3,1},{6,4,1},{7,3,1},{7,6,1},{6,7.5,1 },{3,6,1},{4,5,2},{5,6.5,2},{6,9,2},{3.5,8,2},{6,5,3}, {6,6,3},{9,4,3},{9,5,3},{8,4,4},{9.5,3,4},{10,4,4},{11 ,6,4},{9,6,4},{8,7,5},{10,7,5},{11,9,5},{8,10,5}}; 「Generated從另一個代碼。 –

回答

0
#include <iostream> 

int main() 
{ 
    double MyPoints[25][3] = {{ 
     0, 
    }}; 

    std::string text = "{4,3,1},{6,4,1},{7,3,1},{7,6,1},{6,7.5,1},{3,6,1},{4,5,2},{5,6.5,2},{6,9,2},{3.5,8,2},{6,5,3},{6,6,3},{9,4,3},{9,5,3},{8,4,4},{9.5,3,4},{10,4,4},{11,6,4},{9,6,4},{8,7,5},{10,7,5},{11,9,5},{8,10,5}"; 


    for (int c = 0; c < 25; c++) 
    { 
     std::sscanf(text.c_str(), "{%lf,%lf,%lf},", &MyPoints[c][0], &MyPoints[c][1], &MyPoints[c][2]); 
     text = text.substr(text.find("},") + 2); 
    } 
    // Print Array 
    for (int c = 0; c < 25; c++) 
    { 
     for (int d = 0; d < 3; d++) 
      std::cout << MyPoints[c][d] << " Hellow "; 
     std::cout << std::endl; 
    } 
} 

沒有使用正則表達式或stringstream(幾乎C,而不是C++)的代碼。您還可以通過std::cin >> M[x][y]M[x][y]=value修改二維數組的值。

+0

HJ S ..謝謝你的迴應,我會試試這段代碼並給你一個反饋。 –

+0

HJ S ..爲什麼要用「{%lf,%lf,%lf}, 「? –

+0

您可以在此找到scanf語法(http://en.cppreference.com/w/cpp/io/c/fscanf)。我更喜歡'''在C++中使用'scanf' /'sscanf',但scanf/printf是簡單的工具處理格式化字符串。 –