使用ofstream时,“表达式必须具有常量值”

时间:2013-02-24 09:13:26

标签: c++

我正在使用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说:“无法从'std :: vector&lt; _Ty&gt;'转换参数1到outfile.write()的'const char *'“。

2 个答案:

答案 0 :(得分:3)

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

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

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

你几乎就在那里 - vector<char>是一种正确的方法。要将其传递给ostream::write(),您可以说buffer.data()&buffer[0] -

答案 1 :(得分:0)

您知道sstm.str()为每次通话创建一个新字符串吗?如果缓冲区很大,那将是很多字符串。

您只需创建一个字符串副本即可逃脱:

std::stringstream sstm;

/// *working on stringstream*

std::string buffer = sstm.str();

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

outfile.write(buffer.c_str(), buffer.size());

outfile.close();