2013-09-11 111 views
2

我試圖從csv文件中讀取數據到一個結構向量中,每個結構都包含足球比賽中的各種值(進攻球隊,季度,下場,場地, desc等)。我試圖使用stringstream將字符串轉換爲整數,但我返回垃圾數據。從CSV文件中讀取數據後,將字符串轉換爲int

[email protected],1,47,25,IND,NO,1,10,31,(2:25) J.Addai up the middle to NO 27 for 4 yards (S.Fujita).,0,0,2007 
[email protected],1,46,42,IND,NO,2,6,27,(1:42) P.Manning pass deep left to M.Harrison for 27 yards TOUCHDOWN.,0,0,2007 

我的程序返回的數據是這樣,當我嘗試相關的輸出一切:

Game ID: [email protected] 
Offensive team: IND 
Quarter: 7077994 
Down: 4696320 
To go: 4670480 
Play: (2:25) J.Addai up the middle to NO 27 for 4 yards (S.Fujita). 

Game ID: [email protected] 
Offensive team: IND 
Quarter: 7077994 
Down: 4696320 
To go: 4670480 
Play: (1:42) P.Manning pass deep left to M.Harrison for 27 yards TOUCHDOWN. 

回答

0

istringstream如果你想知道

Data d; //structs 
vector<Data> TeamData; //vector of structs 
string s; 
istringstream iss(s); 

ifstream myfile; 
myfile.open("CSV file here"); //open CSV file 


while ( !myfile.eof() ) 
{ 
getline (myfile, d.gameid, ','); //read to comma, store in d.gameid 

getline (myfile, s, ','); //read to comma 
iss >> d.qtr;    //use stringstream to store into d.qtr 

repeat for remaining values . . . 

CVS的文件類似於這樣複製在構造函數中傳遞它的字符串,因此,對字符串所做的更改對該流沒有任何影響。您應該構造一個新的流,或者每次更改字符串時調用istringstream:str()方法來提供一個新的字符串。

getline (myfile, s, ','); //read to comma 
iss.str(s);    // supply new string to stream 
iss >> d.qtr;    //use stringstream to store into d.qtr 
相關問題