std::getline を利用して任意の文字で文字列を分割する

知らなかったので覚書。

[コード]

#include <iostream>
#include <string>
#include <sstream>
#include <vector>

int
main(){
    std::string input = "homu,mami,mado";
    std::istringstream iss(input);

    std::string str;
    std::vector<std::string> result;
    // , ごとに std::getline で文字列を読みこんでくる
    while( std::getline(iss, str, ',') ){
        result.push_back(str);
    }

    for(auto&& str : result){
        std::cout << str << std::endl;
    }
    
    return 0;
}

[出力]

homu
mami
mado

とりあえず使いたい場合は便利そう。