2013-05-17 22 views
0

獲取運行時錯誤,指出「拋出std :: bad_alloc實例後調用terminate」。不知道怎麼回事,我對C++相當陌生。運行時錯誤與文件io和向量(C++)

do 
    { 
     getline(in_stream, tempstr1); 
     itemNumb.push_back(tempstr1); 
     getline(in_stream, tempstr2); 
     itemNumb.push_back(tempstr2); 
     in_stream >> tempdoub; 
     itemCost.push_back(tempdoub); 
     in_stream >> tempint; 
     itemQuant.push_back(tempint); 
     index++; 
    } while (! in_stream.eof()); 
    in_stream.close(); 

編輯:應該已經明確,itemNumb和ITEMNAME是串矢量,itemCost是雙載體,和itemQuant是整數向量。 tempstr1和2是字符串,tempdoub是double,tempint是整數。

+0

什麼類型是tempstr1-2?它說別的嗎? – gpicchiarelli

+1

字符串太長... – fasked

回答

0

如果任何輸入操作失敗,並且它不是由到達文件結尾引起的,則循環可能是無限的,這最終會導致內存耗盡。

例如:

in_stream >> tempdoub; 

大概讀成double。如果失敗,則流將處於不良狀態(設置了failbit),並且後續讀取將不起作用,並且永遠不會到達文件結尾。立即檢查輸入操作的結果:

while (getline(in_stream, tempstr1) 
     && getline(in_stream, tempstr2) 
     && in_stream >> tempdoub 
     && in_stream >> tempint) 
{ 
    itemNumb.push_back(tempstr1); 
    itemNumb.push_back(tempstr2); 
    itemCost.push_back(tempdoub); 
    itemQuant.push_back(tempint); 
    index++; 
} 
+0

我修改它的方式,它現在沒有做任何事情,所以我確定in_stream >> tempdoub和in_stream >> tempint失敗。任何方式我可以解決這個問題? –