2013-02-24 68 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(); 
相關問題