I'm practicing my parsing, and I'm writing a program with an overloaded function that counts the words in a user entered cstring and regular string. Suprisingly the cstring was easy peasey but the string object is has me a stumped. I don't think my cstring was the most efficient solution, now that I think about it.
so
(1) How should I approach the string case? Seriously stumped on that one (I can use the same approach as I did for the cstring only the lack of NULL at the end complicates things.
(2) What are other ways to accomplish this task with the cstring (can be better or worse than my solution) just want to see other approaches to the problem. As parsing is definatley one of those, several-ways-to-do-it deals.
int main()
{
char *input;
int charLen = 80;
input = new char[charLen];
cout << "Please input a string: ";
cin.getline(input, 80);
string inputS = input;
// cout << "CString ----\n";
// cout << wordCount(input);
cout << endl << "String ----\n";
wordCount(inputS);
delete [] input;
return 0;
}
// ------ FUNCTION: Word Count C-String---------------------------
// Looks to next and previous chars, if alpha followed by space
// then it counts a word.
// ---------------------------------------------------------------
int wordCount(string input)
{
int wCount = 0;
for(int i; i < input.size(); i++)
{
//cout << "input[" << i << "] " << input[i] << " isalpha? " << isalpha(input[i]) << endl;
if((isalpha(input[i]) != 0) && (isalpha(input[i + 1]) == 0))
{
wCount++;
}
if(isalpha(input[input.length() - 1]) == 0 && isalpha(input[input.length()]) != 0)
{
wCount++;
}
}
cout <<"-1 " << input[input.length() - 1] << endl;
cout << "REG " << input[input.length() - 2];
return 0;
}
// ------ FUNCTION: Word Count C-String---------------------------
// Looks to next and previous chars, if alpha followed by space
// then it counts a word.
// ---------------------------------------------------------------
int wordCount(char *input)
{
int wCount = 0;
for(unsigned int i = 0; i < strlen(input); i++)
{
//cout << "input[" << i << "] " << input[i] << " isalpha? " << isalpha(input[i]) << endl;
if((isalpha(input[i]) != 0) && (isalpha(input[i + 1]) == 0))
{
wCount++;
}
}
return wCount;
}