gpt4 book ai didi

c++ - 在 C++ 中使用常量

转载 作者:太空宇宙 更新时间:2023-11-04 15:03:05 25 4
gpt4 key购买 nike

我正在开发一个应该从文件中加载二维数组的程序。

我的文件看起来像这样,第一个数字表示数组的大小:

10
7 6 9 4 5 4 3 2 1 0
6 5 5 5 6 5 4 3 2 1
6 5 6 6 7 6 8 4 3 2
1 5 6 7 7 7 6 5 4 3
5 5 6 7 6 7 7 6 5 9
5 6 7 6 5 6 6 5 4 3
5 6 7 9 5 5 6 5 4 3
5 5 6 7 6 6 7 6 5 4
5 9 5 6 7 6 5 0 3 2
5 5 5 5 6 5 4 3 2 7

到目前为止,这是我的代码:

#include <iostream>
#include <fstream>
using namespace std;

int main() {
ifstream prog;
prog.open("../prog1.dat");

//If file can't be opened, exit
if (!prog) {
cerr << "File could not be opened" << endl;
exit(EXIT_FAILURE);
}
else {
while (!prog.eof()) {
int size = 100, i, j;
prog >> size;
int **numArray = new int* [size];
for(i = 0; i < size; i++) {
numArray[i] = new int[size];
for(j = 0; j < size; j++) {
cout <<numArray[i][j] << " ";
}
cout << endl;
}

prog.close();
return 0;
}
}

}

但是我得到的错误之一是在

int numArray[size][size];

我的部分代码。

我的问题是我不知道如何使它成为常量,因为我从文件中获取大小,就好像我还不知道数组的大小一样。

这是我的第一个 C++ 程序,我几乎是在自学,因为我的教授似乎认为,因为我们应该知道如何用 Java 做这些事情,所以我们不必复习它在类。我发现处理常量的例子说它应该是这样的:

const int size = *value*;

但由于我的程序应该在文件中查找大小,我不确定如何执行此操作。有什么建议么?另外,就像我说的,我在这方面真的很陌生,所以如果您碰巧在我的代码中发现任何其他需要修复的地方,也将不胜感激。

最佳答案

当您在 C++ 中定义数组时,其大小必须在编译时已知。这就是编译器为该行产生错误的原因:

int numArray[size][size];

您可以使用 std::vector 来创建动态数组。

std::vector<std::vector<int>> numArray(size, std::vecot<int>(size));

现在,numArray 可以像静态定义的数组一样使用。

关于c++ - 在 C++ 中使用常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25779963/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com