ok, so I have been working all day on this program and I am kinda stuck. The goal is to have a user input several words, then (ignoring case) alphabetize them (using qsort() only) and count how many times each word was used.

This is what I've got so far:

#include <iostream>
#include <search.h>
#include <string.h>
#include <cctype>
#include <stdio.h>
#include <stdlib.h>
using namespace std;


const int MAX = 100;



void main()
{

	int i=0;
	int length;
	char *delim = " ";
	char *token;
	char string[MAX];
	cout << "Please enter a sequence of words. Press enter when completed" << endl;
	cin.getline(string, MAX);
	length = strlen (string);
	while (i < length)
	{
		string[i] = tolower(string[i]);
		i++;
	}
	cout << "Lower case the words are:\n"
		 << string << endl;


	token = strtok(string, delim);
	int c = 1;
	while (token != NULL)
	{
		
		cout << "token " << c << " is " << endl << token << endl;
		token = strtok(NULL,delim);
		c++;
	}

}

Anyone know where to go from here? Or just how to have each tokenized word saved somehow so I can sort them?

Thanks!

Recommended Answers

All 2 Replies

you will need to store the pointers that are returned by strtok() in an array of pointers so that the words can be sorted by qsort.

char* array[255] = {0}; // assume max of 255 pointers
...
int c = 0; // arrays start at index 0, not 1
while (token != NULL)
{
    cout << "token " << c << " is " << endl << token << endl;
    array[c] = token;
    token = strtok(NULL,delim);
    c++;
}

Now after that you can use qsort to sort the array of pointers.

Thank you, I'll work with that.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.