当整数变量用于在 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++
嗨,我有下面的代码,
# 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";
}
}
相关文章:
- 显示错误输出的简单数组排序程序
- 我是 c++ 的新手.学习基本知识后,我想做井字游戏.对于印刷板,我在下面写代码,但它显示错误
- Clion显示错误,但可以使用Cmake成功构建代码
- 代码使用向量成功运行,但使用数组显示错误
- SDL 映像:无法打开映像,仅显示错误消息
- 为什么将指针重新分配给 1D 数组的 char 时显示错误,但 2D 数组工作正常?
- 与clang++一起使用的VS代码在构建良好的C++文件中显示错误
- 编译器没有显示错误,但我没有得到任何输出.怎么了?
- PPM 颜色显示错误
- 当我选择大于 720 的矩阵大小时,程序退出并显示错误代码.可能是什么原因?
- is_permutation方法从 #include<algorithm> 显示错误的输出
- 为什么使用与父级声明的 std::function 在与子级一起使用时会显示错误?
- 我的代码厨师提交显示错误的结果
- 显示错误"std_lib_facilities.h"
- 为什么C++显示错误的数字?
- Android (ART) 崩溃并显示错误 JNI 在应用程序中检测到错误:jstring 是无效的本地引用
- 这是我的 .h 文件的一些错误,当我在其中包含我的类模板时,它显示 [错误] 未终止 #ifndef
- c++ IF 语句执行,但添加 ELSE 会显示错误
- 内核.cpp在制作 kernel.o 时显示错误和 Makefile 错误
- C++代码编译,但在 Zorin OS 上运行时显示错误