2011-12-08 83 views
0

我試圖將ifstream讀入字符串,我可以在其中設置要讀取的字符數。我已閱讀ifstream.get()ifstream.getline()的文檔,但都沒有完成我想要的。將ifstream的部分讀入字符串對象?

考慮以下字符串:

asdfghjklqwertyuiop

我想在一個隨時間變化的字符數成字符串讀取。我已經開始喜歡這個,但我發現了一個錯誤,沒有的功能,將字符串作爲第一個參數:

string destination; 
int numberOfLettersToGet = 1; 

while (inputstream.get(destination, numberOfLettersToGet)){ 
    //Do something. 
} 

我可以用什麼來代替inputstream.get()

回答

1

你可能喜歡用std::istreamreadgcount成員函數。 get附加一個零終止符,當您讀入std::string時這是不必要的。

std::string destination; 
int numberOfLettersToGet = 1; 

destination.resize(numberOfLettersToGet); 
std::streamsize n = inputstream.gcount(); 
inputstream.read(&destination[0], numberOfLettersToGet); 
destination.resize(inputstream.gcount() - n); // handle partial read 
+0

這隻會第一次工作,因爲'gcount()'返回在最後一個輸入上讀取的字符數,而不是當前流的位置。如果你再讀一次,你將從'n'開始(在最後一次讀取時設置爲'1'),'gcount()'在讀取之後返回1。 1 - 1 = 0 - >空字符串。在'read'之後調整到'gcount()'就足夠了。 – Excelcius

1

istream::get將字符作爲整數返回,因此您只需將返回的字符作爲字符串的下一個字符追加即可。例如

while (string.push_back(inputstream.get())) 
{ //... 
} 
+0

極其低效。 – ThomasMcLeod