MrS*_*S16 4 c++ string boost split
给定一个字符串,如"John Doe,USA,Male",我将如何将字符串与逗号分隔为分隔符.目前我使用升级库,我设法拆分但白色间距导致问题.
例如,上面的字符串一旦拆分成一个向量,只包含"John",而不是其余的.
UPDATE
这是我到目前为止使用的代码
displayMsg(line);
displayMsg(std::string("Enter your details like so David Smith , USA, Male OR q to cancel"));
displayMsg(line);
std::cin >> res;
std::vector<std::string> details;
boost::split(details, res , boost::is_any_of(","));
// If I iterate through the vector there is only one element "John" and not all ?
Run Code Online (Sandbox Code Playgroud)
迭代后,我只得到名字而不是完整的细节
更新:由于您正在阅读cin,因此当您输入空格时,它本质上会停止阅读.它被视为一个停止.因为你正在阅读一个字符串,更好的方法是使用std :: getline
#include <boost/algorithm/string/split.hpp>
#include <boost/algorithm/string.hpp>
#include <iostream>
#include <vector>
using namespace std;
using namespace boost;
int main(int argc, char**argv) {
std::string res;
std::getline(cin, res);
std::vector<std::string> details;
boost::split(details, res, boost::is_any_of(","));
// If I iterate through the vector there is only one element "John" and not all ?
for (std::vector<std::string>::iterator pos = details.begin(); pos != details.end(); ++pos) {
cout << *pos << endl;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出如下:
John Doe
John Doe
USA
Male
Run Code Online (Sandbox Code Playgroud)
虽然您可能想要删除空白.
实际上,你可以毫不费力地做到这一点.
#include <sstream>
#include <string>
#include <vector>
#include <iostream>
int main()
{
std::string res = "John Doe, USA, Male";
std::stringstream sStream(res);
std::vector<std::string> details;
std::string element;
while (std::getline(sStream, element, ','))
{
details.push_back(element);
}
for(std::vector<std::string>::iterator it = details.begin(); it != details.end(); ++it)
{
std::cout<<*it<<std::endl;
}
}
Run Code Online (Sandbox Code Playgroud)