Okay so I was the one with the Assertion failure problem earlier.. so I started all over. I have no compiling errors anymore but now the output is wrong. My new code is:

#include <iostream>
#include <cstring>
using namespace std;

int main()
{
	char phrase[100]; //100 characters allowed 
	char *words[20]; //up to 20 words
	char tok_vals[] = " /n/t";
	int counter = 0;
	char *token;
	char *next_token;

	cout<< "Please enter a phrase: " << endl;
	cin.getline(phrase,100);

	for (int i = 0; i < 20; i++)
	{
		words[i]= "";// initializes the words array with blank strings
	}
	token = strtok_s(phrase, tok_vals, &next_token); //splits phrase into tokens

	while(token != NULL)
	{
		words[counter] = token; //while there are tokens in "string"
		counter ++;

		token = strtok_s(NULL, tok_vals, &next_token); // get the next token
	}
int count;
//print the occurances of each word
for(int i = 0; i < counter; i++)
{ 
	count = 1;
	
	for(int j = (i + 1); j < counter; j++)
	{
		if(strcmp(words[i],words[j]) == 0)
		{
				count++;
				words[j] = "";
		}
		if(words[i] != "")
		{
		     cout << words[i] << "-" << count << "\n";
		}
	}
}

return 0;
}

When the phrase "i am sam" is input into the program, the output is:
i-1
i-1
am-1

I'm not sure of what I need to change. Any help would be appreciated. Thank you for your time.

First, look at your "tok_vals" variable - or what you're assigning to it - use backslashes.

Your counter routine is a bit off. You will never get to count the occurrences of the last item in your phrase (assuming it's unique), since the inner loop will not even execute when the outer loop is positioned on the last item.

You may be better served by building an array of integers, used to store the count of each word, having the same dimension as your word list. As you read off each item from the phrase, search the word list for an entry. If you find it, add one to the corresponding location in the integer array, otherwise, add a new word entry, and set the corresponding entry in the integer array to 1. Then, just rip through the arrays at the end, printing the results.

In C++ this problem would usually be solved using a string and a map. Is there any reason you're not using these?

If you must use strtok and do not want to copy the tokens it finds but instead just point to them like you are trying to do, you will have to restore the null-character to the end of each token, since strtok writes the delimiter characters back.

This article has been dead for over six months. Start a new discussion instead.