gpt4 book ai didi

c++ - 使用 ofstream 时出现 "expression must have a constant value"

转载 作者:行者123 更新时间:2023-11-30 02:56:57 25 4
gpt4 key购买 nike

我正在使用 Visual C++ 将我的游戏从 GNU/Linux 移植到 Windows。

问题是:

std::stringstream sstm;

/// *working on stringstream*

const int size = sstm.str().size();
char buffer[size];

std::ofstream outfile("options", std::ofstream::binary);

for(int i = 0; i < size; i++)
buffer[i] = sstm.str().at(i);

outfile.write(buffer, size);

outfile.close();

它在缓冲区的声明中说:“表达式必须有一个常量值”。

我把它改成了这样:

std::vector<char>buffer(size);

然后 VC 说:“无法在 outfile.write() 中将参数 1 从‘std::vector<_Ty>’转换为‘const char *’”。

最佳答案

const int size = sstm.str().size();
char buffer[size];

buffer这里是可变长度数组(VLA)。根据 C++ 标准,这是非法代码——需要在编译时知道数组的大小。 VLA'a 在 C99 中是允许的,G++ 允许它作为 C++ 中的扩展。

const int可以是编译时常量,如果它是用文字或 ˙ constexpr 初始化的.在你的情况下,它不是。

你快到了 - vector<char>是一种正确的方法。将其传递给 ostream::write()你可以说 buffer.data()&buffer[0] -

关于c++ - 使用 ofstream 时出现 "expression must have a constant value",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15050260/

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