使用令牌解析字符串并分配给变量
parsing string using token and assigning to variables
>这是我的循环
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);
}
将字符串的各个部分分别提取到单个变量中,然后将它们发送到构造函数。
相关文章:
- 将数组的地址分配给变量并删除
- 在 for 循环中定义的临时数组,并分配给属于指针数组的指针
- 如何定义全局函数指针并分配给特定地址
- 如何在构造函数中构造对象并分配引用
- C++如何在函数中传递字符串数组并分配给变量?
- 使用成员函数更改对象或返回并分配它是否被认为是更好的做法?
- 有没有办法获得功能大小并分配内存以复制和执行
- 如何在类构造函数中创建新值并分配给私有unique_ptr
- C 将char []从网络转换为主机订单,并分配给无符号int
- 如何在c++中对向量进行切片并分配给它自己
- 使用令牌解析字符串并分配给变量
- 创建网格并分配值
- 将结构的枚举传递给其他功能并分配值
- C++初始化对象并分配内存
- 如何使用选择语句检索 sqlite 并分配给向量然后分配给字符串
- 通过引用传递结构并分配字符串
- Visual C++ IFstream读取文件并分配给变量
- 从向量读取并分配给对象的成员
- 获取类内"this"的上下文并分配给类指针 TheClass*
- 如何读取CSV文件并分配给特征矩阵