Skip to content

Instantly share code, notes, and snippets.

@donn
Created October 16, 2025 15:06
Show Gist options
  • Select an option

  • Save donn/2f45a0bbd4a1138471407c7716536c73 to your computer and use it in GitHub Desktop.

Select an option

Save donn/2f45a0bbd4a1138471407c7716536c73 to your computer and use it in GitHub Desktop.
strtok_r vs std::getline for parsing paths
#include <vector>
#include <iostream>
#include <sstream>
/*
strtok
"a"
"b"
"c"
"d"
sstream
"a"
""
"b"
"c"
"d"
""
""
""
*/
int main() {
const char *path_str = "a::b:c:d::::";
std::cout << "strtok" << std::endl;
std::string copy{path_str};
char *token = nullptr;
char *rest = &copy[0];
while ((token = strtok_r(rest, ":", &rest))) {
std::cout << '"' << token << '"' << std::endl;
}
std::cout << "sstream" << std::endl;
std::stringstream tokenstream{path_str};
std::string token_s;
while (std::getline(tokenstream, token_s, ':')) {
std::cout << '"' << token_s << '"' << std::endl;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment