Created
October 16, 2025 15:06
-
-
Save donn/2f45a0bbd4a1138471407c7716536c73 to your computer and use it in GitHub Desktop.
strtok_r vs std::getline for parsing paths
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #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 = ©[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