C++ strtok - multiple use with more data buffers

前端 未结 3 797
一生所求
一生所求 2021-01-27 03:41

I have little issue with using strtok() function. I am parsing two files. Firts I load file 1 into buffer. This file constains name of the second file

相关标签:
3条回答
  • 2021-01-27 04:30

    strtok is an evil little function which maintains global state, so (as you've found) you can't tokenise two strings at the same time. On some platforms, there are less evil variants with names like strtok_r or strtok_s; but since you're writing C++ not C, why not use the C++ library?

    ifstream first_file(first_file_name);      // no need to read into a buffer
    string line;
    while (getline(first_file, line)) {
        if (!line.empty() && line[0] == 'f') { // NOT =
            istringstream line_stream(line);
            string second_file_name;
            line_stream.ignore(' ');           // skip first word ("%*s")
            line_stream >> second_file_name;   // read second word ("%s")
            LoadSecondFile(second_file_name);
        }
    }
    
    0 讨论(0)
  • 2021-01-27 04:35

    You can use strtok_r which allows you to have different state pointers.

    0 讨论(0)
  • 2021-01-27 04:37

    Which is why it is constantly recommended to not use strtok (not to mention the problems with threads). There are many better solutions, using the functions in the C++ standard library. None of which modify the text they're working on, and none of which use hidden, static state.

    0 讨论(0)
提交回复
热议问题