我正在开发一个程序,允许用户在学校记录中添加“部门”。部门存储为如下结构:
struct Department{
string ID;
string name;
};
要向记录添加新部门,用户必须输入格式如下的命令:
D [5 digit department ID number] [Department name]
[Department name]
字段是一个字符串,一直延伸到用户按Enter键。因此它可以具有任何数量的空间(例如“人类学”或“计算机科学与工程”)。
当用户正确输入命令字符串(使用getline
获得)时,会将其传递给应提取相关信息并存储记录的函数:
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);
}
不幸的是,我无法弄清楚如何使这种方法有效。我需要一种方法(如果有的话)完成读取iss.str而忽略空格。我设置了noskipws
标志,但是当我测试它时,新记录中的名称字段为空:
...
iss >> discard >> newDept.ID >> noskipws >> newDept.name;
...
我想我错过了关于终止条件/字符的事情。我怎样才能创建我想要的功能......也许是get
甚至是循环的东西?
答案 0 :(得分:3)
我会跳过前导空格,然后阅读其余部分
iss >> discard >> newDept.ID >> ws;
std::getline(iss, newDept.name);