Question

I am working on a program that allows a user to add a "department" to school records. The departments are stored as structs like this:

struct Department{

  string ID;
  string name;
};

To add a new department to the records, the user must enter a command formatted like this:

D [5 digit department ID number] [Department name] 

The [Department name] field is a string that extends until the user presses enter. It can thus have any number of spaces (e.g. "Anthropology" or "Computer Science and Engineering").

When the user inputs the command string correctly (obtained with getline), it is passed to a function that should extract the relevant information and store the record:

void AddDepartment(string command){

  Department newDept;
  string discard;     //To ignore the letter "D" at the beginning of the command 

  istringstream iss;
  iss.str(command);

  iss >> discard >> newDept.ID >> ??? //What to do about newDept.name? 

  allDepartments.push_back(newDept);

}

Unfortunately, I can't figure out how to make this approach work. I need a way (if there is one) to finish reading iss.str while ignoring white spaces. I setting the noskipws flag, but the name field in the new record was empty when I tested it:

... 
iss >> discard >> newDept.ID >> noskipws >> newDept.name; 
...

I suppose I am missing something about termination conditions/characters. How else can I create the functionality I want...maybe something with get or even a loop?

Was it helpful?

Solution

I would skip leading whitespace and then read the rest of the line

iss >> discard >> newDept.ID >> ws;
std::getline(iss, newDept.name);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top