c++ - 用不同的分隔符分割字符串
问题描述
具有以下类型的输入:
add name, breed, birthDate, vaccinationsCount, photograph
(例如add boo, yorkshire terrier, 01-13-2017, 7, boo puppy.jpg
)
我想拆分此字符串以从中获取我的参数,但它不起作用。
我的代码如下所示:
getline(cin, listOfCommands);
string functionToApply = listOfCommands.substr(0, listOfCommands.find(" "));
int position = listOfCommands.find(" ");
listOfCommands.erase(0, position + 1);
cout << listOfCommands;
if (functionToApply == "exit")
break;
else if (functionToApply == "add")
{
position = listOfCommands.find(", ");
string name = listOfCommands.substr(0, position);
listOfCommands.erase(0, position + 1);
position = listOfCommands.find(", ");
string breed = listOfCommands.substr(0, position);
listOfCommands.erase(0, position + 2);
position = listOfCommands.find(", ");
string birthDate = listOfCommands.substr(0, position);
listOfCommands.erase(0, position + 2);
position = listOfCommands.find(", ");
string nrShorts = listOfCommands.substr(0, position);
listOfCommands.erase(0, position + 2);
string photo = listOfCommands;
}
有人能帮助我吗?
解决方案
对于这个示例,我使用带有自定义分隔符的std::getline 、 std::stringstream来帮助解析输入的流和std::vector来存储参数,(如果您愿意,可以将它们分配给您为它们创建的变量):
#include <iostream>
#include <sstream>
#include <vector>
int main() {
std::string listOfCommands, temp, command;
std::vector<std::string> args; //container for the arguments
//retrieve command
getline(std::cin, command, ' ');
if (command == "add") {
getline(std::cin, listOfCommands);
std::stringstream ss(listOfCommands);
while (getline(ss, temp, ',')) { //parse comma separated arguments
while (*(temp.begin()) == ' ')
temp.erase(temp.begin()); //remove leading blankspaces
args.push_back(temp); // add parameter to container
}
//test print
for (std::string str : args){
std::cout << str << std::endl;
}
}
return 0;
}
输入:
add boo, yorkshire terrier, 01-13-2017, 7, boo puppy.jpg
输出:
boo
yorkshire terrier
01-13-2017
7
boo puppy.jpg
推荐阅读
- ruby-on-rails - Rspec json 测试结果的日期格式错误
- android - 为什么我必须将权限添加到清单中,尽管我确实在开始时请求它们
- python - python pil颜色填充
- python - 在烧瓶中提供静态文件,输出是文件名而不是它的内容
- powershell - 根据从文件创建的文件夹将文件复制到文件夹
- python - 将一列 CSV 列表缩减为单个列表
- jmeter - Jmeter Debug Sampler 不显示正则表达式提取器变量
- java - Maven 访问 gcloud
- r - 使用 dplyr 聚合不在组中的值
- xamarin - 创建 zip 文件 xamarin 表单 ios