1

我正在使用 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 *'”。

4

2 回答 2

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]-

于 2013-02-24T09:18:55.923 回答
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();
于 2013-02-24T09:57:22.910 回答