2012-05-27 55 views
0

我試圖從形式的文本文件閱讀:使用此功能讀取文件時不讀字符串流

mdasd tgfor,100,23 
sfier sdfdor,2,3 
mmmmmm,232,452 

:我在各個方面我能想到的,但不能管理到amke它測試工作:

void StudentRepository::loadStudents(){ 
    ifstream fl; 
    fl.open("studs.txt"); 
    Student st("",0,0); 
    string str,s; 
    stringstream ss; 
    int i; 
    int loc; 
    if(fl.is_open()){ 
     while(getline(fl,str)){ 
      cout<<"string: "<<str<<endl; 

      loc = str.find(","); 
      ss << str.substr(0,loc); 
      s = ss.str(); 

      cout<<"name: "<<s<<endl; 

      st.setName(s); 
      ss.str(""); 
      str.erase(0,loc+1); 

      loc = str.find(","); 
      ss << str.substr(0,loc); 
      ss >> i; 

      cout<<"id:"<<i<<endl; 

      st.setId(i); 
      ss.str(""); 
      str.erase(0,loc); 
      ss >> i; 
      st.setGroup(i); 
      ss.str(""); 

      cout<<"gr:"<<i<<endl; 
      students.push_back(st); 

      cout<<endl; 
     } 
    } 
    else{ 
     cout<<"~~~ File couldn't be open! ~~~"<<endl; 
    } 
    fl.close(); 
} 

但我可以告訴你在礦井運行它比一切的第一行只讀的第一個名字是空白:

string: mqqeeqw tuwqer,23,32 /// ID AND GROUP are initializate with 0 thats 
name: mqqeeqw tuwqer   /// why they have that values... why does it not work? 
id:0 
gr:0 

string: maier tudor,2,3 
name: 
id:0 
gr:0 

string: maier tudor,0,0 
name: 
id:0 
gr:0 
+0

是你應該在這裏使用一個字符串流?我不認爲它有什麼好處。 –

+0

將mstring轉換回整數:\ –

回答

4

您可以在std::stringstream使用getline()與自定義分隔符,這樣的:

if(fl.is_open()){ 
    while(getline(fl,str)){ 
     stringstream ss(str); 
     string name, id, gr; 
     while(ss) { 
      getline(ss, name, ','); // "," as delimiter 
      getline(ss, id, ','); 
      getline(ss, gr, ','); 
     } 

     cout << "name: " << name <<endl; 
     cout << "id:" << id << endl; 
     cout << "gr:" << gr << endl; 
     cout << endl; 
    } 
} 
+0

omg真的嗎?感謝一堆:0 –

+0

你仍然必須從'std :: string'獲取'int's,儘管 – bbtrb

+0

管理謝謝你...我有很多問題,因爲我的手工sub-delimitators等等,但我工作得很好現在:)再次感謝你, –