使用令牌解析字符串并分配给变量

parsing string using token and assigning to variables

本文关键字:串并 分配 变量 字符串 字符 令牌      更新时间:2023-10-16

>这是我的循环

while(getline(iss,token,','))
     cout<<token<<endl;

有问题的字符串是:

约翰·doe,freshman,email@email.com

运行 while 离开输出:

john doe
freshman
email@email.com

我的目标是将解析字符串的每一部分分配给一个变量。例:

name = token;
cout<<"name: "<<name<<endl:

将产生

name: John doe

然后我会重复其他 2 件。问题是我无法弄清楚将令牌分配给姓名、年份和电子邮件,而不会在每次通过循环时覆盖。

 90   string comma;
 91   string line;
 92   string token;
 93   ifstream myfile("student.dat");
 94   string name,email="";
 95   string status="";
 96   int id,i;
 97   if (myfile.is_open()){
 98     while ( getline (myfile,line) ) {
 99         //parse line
100         string myText(line);
101         cout<<line<<endl;
102         istringstream iss(myText);
103         if (!(iss>>id)) id=0;
104         i = 0;
105         while(getline(iss,token,','))
106         {
107             cout<<token<<endl;
108            
109            
110                 
111                
112            
113
114            
115         }
116         Student newStudent(id,line,"","");
117         Student::studentList.insert(std::pair<int,Student>(id,newStudent));

你可能想要这样的东西:

std::string name, year, email;
if (std::getline(iss, name, ',') &&
    std::getline(iss, year, ',') &&
    std::getline(iss, email))
{
     newStudent = Student(id, name, year, email);
}

将字符串的各个部分分别提取到单个变量中,然后将它们发送到构造函数。