How to use stringstream to separate comma separate

2019-01-03 08:26发布

This question already has an answer here:

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

3条回答
聊天终结者
2楼-- · 2019-01-03 08:33
#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

查看更多
时光不老,我们不散
3楼-- · 2019-01-03 08:43

Maybe this code will help you:

stringstream ss(str);//str can be any string    
int integer;
char ch;
while(ss >> a)
{
    ss>>ch;  //flush the ','
    cout<< integer <<endl;
}    
查看更多
对你真心纯属浪费
4楼-- · 2019-01-03 08:51
#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';
    }
}
查看更多
登录 后发表回答