C++でURLエンコード/パーセントエンコード
ネットで見つけたものがうまく動かなかったから自分で書いた。space_to_plusをtrueにするとスペースが(%20ではなく)+記号になるようにした。
#include <string> #include <sstream> #include <iomanip> std::string url_encode(const std::string& str, bool space_to_plus = false) { std::ostringstream buf; buf << std::hex << std::setfill('0'); typedef std::string::const_iterator Iterator; Iterator end = str.end(); for(Iterator itr = str.begin(); itr != end; ++itr) { if((*itr >= 'a' && *itr <= 'z') || (*itr >= 'A' && *itr <= 'Z') || (*itr >= '0' && *itr <= '9') || *itr == '-' || *itr == '.' || *itr == '_' || *itr == '~') { buf << *itr; } else if(space_to_plus && *itr == ' ') { buf << '+'; } else { buf << '%' << std::setw(2) << static_cast<int>(static_cast<unsigned char>(*itr)); } } return buf.str(); }