简体   繁体   中英

C++: problems with strtok

I need to break into words the text that the array of characters s holds. I attempted to do that with strtok but i get the error: invalid conversion from 'char' to 'const char*' . What am I doing wrong?

Here's the code:

char s[101];
char* p[100];
int main()
{
    cin.getline(s, 100, '\n');
    p = strtok(s, ' ');
    while (p) {
        p = strtok('\0', ' ');
    }
    return 0;
}

Probably what you want:

int main()
{

    char s[101] = {};
    char* p = nullptr;
    cin.getline(s, 100, '\n');
    p = strtok(s, " ");
    while (p) {
        p = strtok(nullptr, " ");
    }
    return 0;
}

Both parameters of strtok() are char* pointers, but you are trying to pass single char values instead, hence the error.

Also, strtok() returns a char* , which you are the trying to assign to a char*[] array, which will not work, either. Drop the array and just use a single pointer.

Try this:

int main() {
    char line[101];
    std::cin.getline(line, 100, '\n');
    char *word = strtok(line, " ");
    while (word) {
        // use word as needed...
        word = strtok(NULL, " "); // or nullptr in C++11 and later
    }
    return 0;
}

That being said, you really should not be using C semantics in C++ code. In this case, you should use std::string and std::istringstream instead:

#include <iostream>
#include <sstream>
#include <string>

int main() {
    std::string line, word;
    std::getline(std::cin, line);
    std::istringstream iss(line);
    while (iss >> word) {
        // use word as needed...
    }
    return 0;
}

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