2017-03-07 89 views
-1

這裏我只是想輸入文件數據寫入我的類變量。類變量是公共的並且作爲通用變量。互聯網上有類似的話題,但花了數小時後,我仍然無法解決這個錯誤。如果我改寫((myfile >> map.at(i).x_p >> map.at(i).f)),那麼會有好的,但這並不可取。我的文件Book1.csv列示如下:C++讀取文件並寫入變量時出現未處理的異常 - getline錯誤?

9, 2.25 
7, 3 
5, 3 
3, 3 
1, 2.25 

對於每一個對象,我還想寫2個變量,我寫我的代碼上的Visual Studio 2013快。 我很感激任何提示和建議。

這是我的代碼。

class node {   
    public: 
    string x_p;  
    string f;  // force 
    }; 

int _tmain(int argc, _TCHAR* argv[]) 
{ 
vector<node> map(5); 

ifstream myfile; 
myfile.open("Book1.csv"); 

if (myfile.is_open()) 
{ 
    while ((getline(myfile, map.at(i).x_p, ','))) // close the loop when the file reading reaches its end 
    { 
     cout << "KK" << endl;  
//  getline(myfile, map.at(i).x_p, ','); 
     getline(myfile, map.at(i).f); 
     cout << map.at(i).x_p << ", " << map.at(i).f << endl; 
     ++i; 


    } 
    myfile.close(); 

} 
else cout << "Unable to open file"; 

cout << "end" << endl; //test 

system("pause"); 
return 0; 

}

+0

你確切的錯誤是什麼? –

+1

請提供MCVE。你當前的代碼甚至不會編譯。例如,'i'變量沒有被定義。 – Ari0nhh

回答

0

代碼成功讀取五行。然後它嘗試讀取第六個。如果at(i)沒有拋出一個異常,試圖進入五行元素的第六個元素vectorstring將第六行寫入可能的第六行,那麼第六個getline會從文件末尾反彈,失敗並退出循環。

可能的解決辦法:

while (i < map.size() && 
     getline(myfile, map.at(i).x_p, ',') && 
     getline(myfile, map.at(i).f))) 

也得到了太很快結束的行消除不良行爲的脆性。

+0

而(I <5)\t // CH是用來寫在附圖 \t \t { \t \t \t MYFILE >> map.at(ⅰ).x_p >> CH >> map.at之間的逗號(如果; \t ............ } 我試過了,它也起作用了。我認爲你的方式會成功。 感謝您爲我編輯。 我不知道如何添加代碼標籤。 – kd37

+0

@ kd37標籤不是我。我只是讓你的輸入文件中的換行可見。 – user4581301

相關問題