How to use stringstream to separate comma separated strings [duplicate]

僤鯓⒐⒋嵵緔 提交于 2019-11-26 03:47:49

问题


This question already has an answer here:

  • How do I iterate over the words of a string? 76 answers

I\'ve got the following code:

std::string str = \"abc def,ghi\";
std::stringstream ss(str);

string token;

while (ss >> token)
{
    printf(\"%s\\n\", token.c_str());
}

The output is:

abc
def,ghi

So the stringstream::>> operator can separate strings by space but not by comma. Is there anyway to modify the above code so that I can get the following result?

input: \"abc,def,ghi\"

output:
abc
def
ghi


回答1:


#include <iostream>
#include <sstream>

std::string input = "abc,def,ghi";
std::istringstream ss(input);
std::string token;

while(std::getline(ss, token, ',')) {
    std::cout << token << '\n';
}

abc
def
ghi




回答2:


#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
    std::string input = "abc,def,   ghi";
    std::istringstream ss(input);
    std::string token;
    size_t pos=-1;
    while(ss>>token) {
      while ((pos=token.rfind(',')) != std::string::npos) {
        token.erase(pos, 1);
      }
      std::cout << token << '\n';
    }
}


来源:https://stackoverflow.com/questions/11719538/how-to-use-stringstream-to-separate-comma-separated-strings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!