The old version was similar to strtok and used local storage of global flows to store the position at the end of the last token.
The problem with the approach used is that it does not allow nesting functions such as strtok / wcstok .
Imagine we have a row like "r0c0;r0c1\nr1c0;r1c1" (a table with two rows and two columns), and we want to split it into rows first and then divide each row into columns.
For this we need 2 cycles. Using the old approach, this is not possible, since the nested loop will overwrite the state of the outer loop. With the new approach, each cycle can have a separate state stored in separate variables:
#include <cwchar> #include <iostream> int main() { wchar_t input[] = L"r0c0;r0c1\n" L"r1c0;r1c1"; wchar_t *rowstate; wchar_t *row = std::wcstok(input, L"\n", &rowstate); while (row != nullptr) { std::wcout << L"Row: " << row << std::endl; wchar_t *colstate; wchar_t *col = std::wcstok(row, L";", &colstate); while (col != nullptr) { std::wcout << " Col: " << col << std::endl; col = std::wcstok(nullptr, L" ", &colstate); } row = std::wcstok(nullptr, L" ", &rowstate); } }
Exit:
Row: r0c0;r0c1 Col: r0c0 Col: r0c1 Row: r1c0;r1c1 Col: r1c0 Col: r1c1
source share