I am attempting to extract words from a c string and then compare then with the words in a 2d array and count the number of matching words. I've noticed that some of the string lengths are not what I was expecting and that's probably why numMatches isn't correct but I'm not sure why I'm getting string lengths that don't match. Where am I going wrong here?
#include <iostream>
using namespace std;
#include <string.h>
int main ()
{
char str[] ="bob amy ted susan";
char * pch;
pch = strtok (str," ");
char arr[4][10] = {"bob", "amy", "susan", "ted"};
int numMatches = 0;
int i = 0;
while (pch != NULL)
{
cout<< pch <<endl;
cout << strlen(arr[i]) << endl;
if (strcmp(pch,arr[i])==0){
numMatches++;
}
pch = strtok (NULL, " ");
i++;
}
cout << arr[2] << endl;
cout << numMatches << endl;
return 0;
}
Output I'm getting...
bob
3
amy
3
ted
5
susan
3
Total Matches : 2
Output I'm expecting...
bob
3
amy
3
ted
3
susan
5
Total Matches : 4