0

I am new to C++. While I was learning the strtok() function, I tried to cout after execution of the function, but I can't understand why the cout is not executing.

#include<iostream>
#include<cstring>
#include<climits>
#include<string> 
#include<algorithm>
using namespace std;

int main() {
    char s[100]="today is a rainy day";
    char *ptr=strtok(s," ");
    cout<<ptr<<endl;
    while(ptr!=NULL){
        ptr=strtok(NULL," ");
        cout<<ptr<<endl;
    } 
    cout<<"Hello";
    return 0;
}

Please help me understand where this goes wrong.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Akishere
  • 37
  • 5

3 Answers3

3

Sooner or later ptr=strtok(NULL," ") will return a null pointer. Which you immediately try to output leading to a null-pointer dereference and undefined behavior (and a very probable crash).

I suggest you modify your loop to something like this:

char *ptr = std::strtok(s, " ");
while (ptr != nullptr)
{
    std::cout << ptr << '\n';
    ptr = std::strtok(nullptr, " ");
}

Note the order in which things are done, and which guarantees that ptr will never be a null pointer when you output it.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
1

Change

while (ptr!=NULL)

to

while ((ptr = strtok(NULL, " ")) != NULL)

And erase the line with the call to strtok.

After "day" is printed, ptr is set to "day", not NULL, so the next iteration of the loop is executed. But then strtok is called and ptr is set to NULL. Trying to cout with a NULL ptr is what gives you undefined behavior.

Should look like this

#include<iostream>
#include<cstring>
#include<climits>
#include<string> 
#include<algorithm>
using namespace std;
int main() {
    char s[100] = "today is a rainy day";
    char *ptr = strtok(s, " ");
    cout << ptr << endl;
    while ((ptr = strtok(NULL, " ")) != NULL) {
        cout << ptr << endl;
    }

    cout << "Hello";
    return 0;
}
Nasrat Takoor
  • 344
  • 3
  • 8
  • 2
    `cout`ing a `nullptr` will not 'give an error'. It gives the program undefined behaviour. Then it might seem to work correctly, give an error, read a poem, make toast, or infinite other things in between. One cannot rely on getting an error; one simply must avoid writing code that has UB. – underscore_d Nov 09 '20 at 15:41
0
#include<iostream>
#include<cstring>
#include<climits>
#include<string>
#include<algorithm>
using namespace std;

int main() {
    char s[100]="today is a rainy day";
    char *ptr=strtok(s," ");
    //cout<<ptr<<endl; // you can remove this line
    while(ptr!=NULL){
        cout<<ptr<<endl; // use cout upper the prt=strtok(NULL," "); 
        ptr=strtok(NULL," ");
        //cout<<ptr<<endl;  //problem here in your code.
    }
        cout<<"Hello There!";
        return 0;
}