给定一个字符串,例如“John Doe,USA,Male”,我将如何使用逗号作为分隔符来拆分字符串。目前我使用的是 boost 库,我设法拆分,但白色间距会导致问题。
例如,上面的字符串一旦被拆分成一个 vector ,就只包含“John”而不包含其余部分。
更新
这是我目前使用的代码
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 ?
迭代后我只得到名字而不是完整的细节
最佳答案
实际上,您可以在没有 boost 的情况下做到这一点。
#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;
}
}
关于c++ - 拆分 C++ 字符串 boost ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20916232/