[英]Reading from file not reading stringstream
我正在嘗試從以下形式的文本文件中讀取內容:
mdasd tgfor,100,23
sfier sdfdor,2,3
mmmmmm,232,452
使用此功能:我可以想到的所有方式進行測試,但無法設法使其發揮作用:
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
您可以在帶有自定義分隔符的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;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.