The nice thing with strtok is that you don't need a second copy of the words.
I see several problems with your current code. I'll describe them first and then give some code to parse the file with strtok.
Line 10: names is uninitialized, so size will be some random number.
Line 14: You allocate space for only 64 words.
Line 16: You read just one line. Can the infile look like this:?
This is a test
That's one small step for a man
One giant leap for mankind.# |
Line 19. If there are two spaces together then it will think there are two words.
Line 25: you're allocating too much space for each word. I suggest that you change "name" and "name2" to "buffer" and "words" to keep to it clear which is which. Then change MAX and MAX_SIZE_OF_A_NAME to MAX_BUFFER_SIZE and MAX_WORD_SIZE. Although as you'll see below, you won't need MAX_WORD_SIZE if you use strtok
Line 27: You're copying the entire buffer into each word.
So here is some code that will read the file and parse out the words. Read the links on how strtok() works. make sure you understand this code and then add code at the end to sort the words and print them out in sorted order.
Once you have the words sorted, it's pretty easy to count the number of occurences of each.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
|
#include <iostream>
#include <cstring>
using namespace std;
const int MAX_BUFFER_SIZE = 1000;
const int MAX_WORDS = MAX_BUFFER_SIZE/4;
char buffer[MAX_BUFFER_SIZE]; // holds the whole input buffer
char *words[MAX_WORDS]; // points to words within the buffer
int main() {
cin.getline(buffer, MAX_BUFFER_SIZE, '#'); // http://www.cplusplus.com/reference/istream/istream/getline/
// Parse out the words.
// http://www.cplusplus.com/reference/cstring/strtok/
unsigned numWords = 0;
for (char *cp = strtok(buffer, " \t\n#"); cp; cp = strtok(nullptr, " \t\n#")) {
words[numWords++] = cp;
}
cout << "total words: " << numWords << endl;
// Print the (unsorted) words
for (size_t i = 0; i < numWords; ++i) {
cout << words[i] << '\n';
}
}
|