2014-01-07 21 views
0

您好聲明數組大小我有下面的代碼,錯誤顯示爲「表達必須有一個常數值」當整數變量被用於C++

# include <iostream> 
# include <limits> 

using namespace std; 

int main() 
{ 
    int runs,innings,timesnotout,n; 
    cout<<"Enter the number of players:"; 
    cin>>n; 
    const char name[n][10]; //here error shows as "Expression must have a constant value" is displayed 


} 

我試圖獲取從輸入的n值,然後使用作爲數組大小的n值

+0

的載體中。可變長度數組不是標準的。 – chris

+2

並使用'std :: string' – olevegard

+0

所以使用'std :: vector names(n);' – Jarod42

回答

2

這意味着錯誤信息的確切含義。你只能使用常量表達式聲明數組。在你的情況下,最好使用std::vector<std::string>甚至std::vector<std::array<char, 10 >>或在堆中分配數組。

+0

我想你的意思是'std :: vector ',因爲他似乎打算閱讀以球員的名義。 –

+0

@ Zac Howland你是對的。這是我的錯字。我會更新我的帖子。謝謝。 –

+0

@ Zac Howland謝謝:) – user3027039

1

如果你打算讓每個玩家的統計數據,你應該定義一個結構/類的這樣的載體:

struct PlayerStats 
{ 
    std::string Name; 
    unsigned int Runs; 
    unsigned int Innings; 
    unsigned int TimesNotOut; 
}; 

int main() 
{ 
    unsigned int n = 0; 
    std::cout << "Enter number of players: "; 
    std::cin >> n; // some error checking should be added 
    std::vector<PlayerStats> players(n); 
    // ... etc 
    return 0; 
} 
+0

@ Zac Howland謝謝:) – user3027039

0

當你想存儲的東西事先不知道大小,您可以使用向量。因爲它可以在執行程序期間動態增長。

在你的情況,你可以使用類似:

#include <iostream> 
#include <vector> 

using namespace std; 

int main() { 

    std::vector<string> nameVec; 

    nameVec.push_back("John"); 
    nameVec.push_back("Kurt"); 
    nameVec.push_back("Brad"); 
    //Warning: Sometimes is better to use iterators, because they are more general 
    for(int p=0; p < nameVec.size(); p++) { 
    std::cout << nameVec.at(p) << "\n"; 
    } 

} 
+0

@ user215507謝謝:) – user3027039

相關問題