简体   繁体   中英

C++ strtok function split words

i am to write a function called splitLine() in c++. can someone please help? im really confused

splitLine () {

    string temp = aLine;
    string *tempLine =  strtok(temp, " ");
    free(temp)
    countNum = sizeOf(tempLine);

   }

You're misunderstanding the instructions.

The strtok function operates on nul terminated char arrays (aka C strings) not C++ strings. So create a temporary 'string' actually means this

// create temporary string which is a copy of aLine
char* temp = new char[aLine.size() + 1];
strcpy(temp, aLine.c_str());

// extract words from temp
...

// free temporary string
delete[] temp;

Breaking the temporary string into words with strtok means writing a loop . strtok will extract one word at a time. I'm sure you can find examples of this on the internet. So I'll leave that to you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM