Error time & Compile error


  • 0
    S

    At the first time, I wrote the following code, and it ran smoothly in my computer, and no bugs were presented. However, when i submitted the code, it always displayed with "Time error"

    void reverseWords(string &s) 
    {
    	vector<string> word;
    	char *cstr = new char[s.length()];
    	strcpy(cstr, s.c_str());
    
    	s.clear();
    	char *tokenPtr = strtok(cstr, " ");
    
    	while(tokenPtr != NULL)
    	{
    		word.push_back(tokenPtr);
    		tokenPtr = strtok(NULL, " ");
    	}
    	
    	for(int i = word.size() - 1; i > 0 ; i--)
    	{
    		s.append(word.at(i));
    		s.append(" ");
    	}
    
    	s.append(word.at(0));
    }
    

    then, i thought manby it is because the strtok function is not safe that cause theTime Error. I tried with the safe function strtok_s, and samely, the code run correctly in my computer, but unluckly, it hints with "Complie error: strtok_s is undeclared"!!!

    void reverseWords(string &s) 
    {
    	vector<string> word;
    	char *pNext = NULL;
    	char *cstr = new char[s.length()];
    	strcpy(cstr, s.c_str());
    
    	s.clear();
    	char *tokenPtr = strtok_s(cstr, " ", &pNext);
    
    	while(tokenPtr != NULL)
    	{
    		word.push_back(tokenPtr);
    		tokenPtr = strtok_s(NULL, " ", &pNext);
    	}
    	
    	for(int i = word.size() - 1; i > 0 ; i--)
    	{
    		s.append(word.at(i));
    		s.append(" ");
    	}
    
    	s.append(word.at(0));
    }
    

    Who can help me with these bugs, i can't make it by myself.
    THX!


  • 1
    S

    First of all strtok_s is a non-standard function provided only by Microsoft. You are not supposed to use it for portable applications.

    Secondly, it is not necessarily strtok that triggers the runtime error, but the way you write your code. You must add handling for the case when s is an empty string.

    Last but not the least, if I were the interviewer, I'll ask you to implement strtok by yourself. Try to do this in place without using lib functions and extra containers.


  • 0
    S

    I have tried another method in dealing with this issue. Thank you for your sincerely and useful answer. I am a freshman in LeetCode, and your tips are appreciated greatly. Thanks!


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.