2013-02-24 33 views
1

我使用Visual C++将我的游戏从GNU/Linux移植到Windows。“表达式必须具有恒定值”,同时使用ofstream

这里的问题是:

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 “不能 '的std ::矢量< _Ty>' 到 '为const char *' 转换参数1”( )。

回答

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

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(); 
相关问题