读入具有任意数目空格的部分输入字符串

Reading in part of an input string with arbitrary number of spaces

本文关键字:输入 字符串 空格 任意数      更新时间:2023-10-16

我正在编写一个程序,允许用户在学校记录中添加一个"系"。部门以如下结构体的形式存储:

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

不幸的是,我不知道如何使这种方法工作。我需要一种方法(如果有的话)来完成阅读。STR同时忽略空格。我设置了noskipws标志,但是当我测试它时,新记录中的名称字段是空的:

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

我想我错过了一些关于终止条件/字符。我还能如何创建我想要的功能呢?也许是get或者甚至是一个循环?

我会跳过前导空格,然后读取该行的其余部分

iss >> discard >> newDept.ID >> ws;
std::getline(iss, newDept.name);