I'm stuck with this exercise. It suppose to read a text[30] and return the number of words that contains but always returns (int) 1 instead of the right value. When trying to debug it, I added a printf call as a last statement into each "branch" of the if statement, (which is contained in a while loop), in the countWords function. Compiling and executing it after this makes the program to return the correct number of words. I'm pretty sure there should be something wrong in the code but I can't find the mistake. If not, is printf affecting it in any way? Any suggestion about whole the code is welcome. Regards.
int main (void)
{
void readText (char [], const int);
int countWords (char []);
void printResult (int);
const int upBound = 30;
char string[upBound];
int result;
printf ("Write a text and press 'return' an extra time when done\n\n");
readText (string, upBound);
result = countWords (string);
printf ("\nThe text is %d word(s) long.", result);
return 0;
}
The next two functions read the text.
int readLine (char line[], const int upBound)
{
static int i = 0;
char tmp;
do
{
tmp = getchar ();
if (i < (upBound - 1))
{
line[i++] = tmp;
}
}
while ((tmp != '\n'));
return i;
}
void readText (char fString[], const int upBound)
{
int readLine (char [], const int);
int i;
while ((fString[(i = readLine (fString, upBound)) - 2] != '\n')
&& (i < (upBound - 1)));
if (i == (upBound - 1)) fString [(upBound - 1)] = '\0';
else fString[--i] = '\0';
}
The last two functions should count the words and test whether characters are alphabetic or white spaces respectively.
int countWords (char fString[])
{
bool testAlphabetic (char);
int i = 0, counter = 0;
bool lfw = true;
while (fString[i] != '\0')
{
if ((lfw) && (testAlphabetic (fString[i])))
{
++counter;
lfw = false;
++i;
printf ("1"); // This is the test
}
else if (!(testAlphabetic (fString[i])))
{
lfw = true;
++i;
printf ("2"); // This is the test
}
else
{
++i;
printf ("3"); // This is the test
}
}
return counter;
}
bool testAlphabetic (char character)
{
bool isAlphabetic;
if (((character >= 'a') && (character <= 'z')) || ((character >= 'A') && (character <= 'Z')))
{
isAlphabetic = true;
}
return isAlphabetic;
}