2009-03-01 118 views
1

我要實現以下有一個字符緩衝區,我試圖將代碼移植放流中的此字符緩衝區,然後再執行得到這樣實現istream獲取字符緩衝區?

char *buffer; //this is initialized 
int bufferSize; //this is initlized 
std::istringstream inputStream (std::string(buffer, bufferSize)); 
int getVal = inputStream.get(); 

編輯:是上面的代碼優化,其中,對於getVal,您將整個緩衝區複製到一個流中,然後在流上執行操作。

如何從緩衝區本身獲取getVal值。

回答

1

我不相信它是最優的,只是因爲構建一個std :: string可能會導致整個緩衝區的副本。然而,istringstream的使用看起來很好。

要直接從緩衝區得到,你可以做這樣的事情:

int bufferPos = 0; 

char getFromBuffer() 
{ 
    if (bufferPos < bufferSize) 
    { 
    return buffer[bufferPos++]; 
    } 
    else 
    { 
    return 0; 
    } 
} 

您可能希望把更好的界面上這一點,雖然。用char *構建istringstream可能會有更好的方法,但我在快速瀏覽文檔時沒有看到它。

+0

Minor nitpick:不應該得到()在EOF返回-1? – 2009-03-01 22:22:16