gpt4 book ai didi

c++ - 从文件中读取而不是读取字符串流

转载 作者:行者123 更新时间:2023-11-27 23:23:54 24 4
gpt4 key购买 nike

我正在尝试从以下格式的文本文件中读取:

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;
}
}

关于c++ - 从文件中读取而不是读取字符串流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10775864/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com