0

I'm trying to use the function strtok to tokenize an input from the user and then print out the result with new lines between each word. However, this error pops up.

#include <iostream>
#include <stdio.h>
#include <string.h>

using namespace std;

int main()
{
    string str;
    char *tokenPtr;

    cout << "Enter a sentence : " << endl;
    getline(cin, str);

    tokenPtr = strtok( str, " " ); // ERROR: No matching function for call to 'strtok'
    while( tokenPtr != NULL ) {
        cout << tokenPtr << endl;
        tokenPtr = strtok( NULL, " " );
    }

    return 0;
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Naoki Atkins
  • 9
  • 1
  • 3

1 Answers1

1

The standard C function strtok is used with character arrays that contain strings.

So its first parameter has the type char * while you are supplying an argument of the type std::string.

You can use instead a standard string stream std::istringstream, For example

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

int main() 
{
    std::string s;

    std::cout << "Enter a sentence : ";

    std::getline( std::cin, s, '\n' );

    std::string word;

    for ( std::istringstream is( s ); is >> word; )
    {
        std::cout << word << '\n';
    }

    return 0;
}

The program output might look like

Enter a sentence : Hello Naoki Atkins
Hello
Naoki
Atkins
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335