0

here is my loop

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

the string in question is:

john doe,freshman,[email protected]

running the while leave outputs:

john doe
freshman
[email protected]

My goal is to assign each piece of the parsed string to a variable. example:

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

would produce

name: John doe

Then i would repeat for the other 2 pieces. Problem is I can't figure out to assign token to name, year, and email without it overwriting with each pass through the loop.

 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));
0

1 Answer 1

0

You probably want something like this:

std::string name, year, email;

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

Extract parts of the string into individual variables respectively, then send them over to the constructor.

Sign up to request clarification or add additional context in comments.

3 Comments

That doesn't see to work because it first says newStudent there is no output when I go to print out the contents of the map.
The only thing being printed is the id number. It doesn't look like anything is being stored in name, year, email.
It turns out all you need to do is ignore() before performing the first getline() call.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.