当整数变量用于在 c++ 中声明数组大小时,错误显示为"Expression must have a const value"

Error shows as "Expression must have a const value" when integer variable is used for declaring array size in c++

本文关键字:显示 错误 Expression must value const have 小时 用于 变量 整数      更新时间:2023-10-16

嗨,我有下面的代码,

# 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 值用作数组大小

这完全是指错误消息所说的内容。您只能使用声明数组的常量表达式。在您的情况下,最好使用 std::vector<std::string> 甚至std::vector<std::array<char, 10>>' 或在堆中分配数组。

如果你打算保留每个玩家的统计数据,你应该定义一个结构/类和一个向量:

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;
}

当您想在事先不知道大小的情况下存储某些内容时,可以使用向量。因为它可以在程序执行期间动态增长。

在您的情况下,您可以使用以下内容:

#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";
   }
}