【问题标题】:Reading in part of an input string with arbitrary number of spaces读取具有任意数量空格的输入字符串的一部分
【发布时间】:2013-01-21 22:56:36
【问题描述】:

我正在开发一个允许用户将“部门”添加到学校记录的程序。部门存储为如下结构:

struct Department{

  string ID;
  string name;
};

要将新部门添加到记录中,用户必须输入格式如下的命令:

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

[Department name] 字段是一个一直延伸到用户按下回车键的字符串。因此它可以有任意数量的空间(例如“人类学”或“计算机科学与工程”)。

当用户正确输入命令字符串时(通过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标志,但是测试时新记录中的name字段为空:

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

我想我遗漏了一些关于终止条件/字符的内容。我还能如何创建我想要的功能......也许是 get 甚至是循环?

【问题讨论】:

    标签: c++ string input stringstream istringstream


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-11
      相关资源
      最近更新 更多