读入具有任意数目空格的部分输入字符串
Reading in part of an input string with arbitrary number of spaces
我正在编写一个程序,允许用户在学校记录中添加一个"系"。部门以如下结构体的形式存储:
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);
相关文章:
- C++,在int数组中输入字符串或字符会输出0,而不是ascii或error
- 用户输入字符串的文件附加问题..C++
- 从 cin 读取不会返回整个输入字符串
- 输出返回编号。等于输入字符串的单词的字符串数
- 控制台未正确读取输入字符串
- 使用终止程序的指针在数组中输入字符串
- 如何删除用户输入字符串末尾的空字符?
- 在循环中使用 cin.get() 输入字符串
- 如何从输入字符串中提取特定位置的字符?
- 用户输入字符串的结构的搜索向量
- 无法使用 getline() 输入字符串.它只读取一个字符串
- 如何在 c++ 中读取输入字符串,忽略空格
- FSTREAM的问题读取确定,但不编写用户输入字符串
- boost::split会在输入字符串不是常量时更改输入字符串吗?
- 通过键盘输入字符串数组和 int 数组的数组大小
- Zlib 放气输入大于原始输入字符串的字符
- C 忽略输入字符串
- 获取一个输入字符串,将其转换为其十六进制值,然后将其十六进制存储为 int
- 我无法将 Excel 中的输入字符串存储为二维字符串
- 如何识别输入的输入字符串在 c++ 中是两个还是多个单词