I’m trying to create 3 functions, one for counting words, one for counting letters, and another to print the average of letters and words. Im getting an error in xcode i dont understand in the last function (printing_average()) printf…
Appreciate your help.
My code:
...main()
int num_of_words()
{
int userInput;
int numOfWords = 0;
while ((userInput = (getchar())) != EOF)
{
while (userInput != ' ')
{
if (userInput == ' ')
numOfWords++;
}
}
return numOfWords;
}
int num_of_letters()
{
int userInput;
int numberOfLetters = 0;
while ((userInput = (getchar())) != EOF)
{
if (ispunct(userInput) && numberOfLetters > 0)
{
numberOfLetters--;
}
else if(userInput == 'n' && numberOfLetters > 0)
{
numberOfLetters--;
}
else if (userInput == ' ' && numberOfLetters > 0)
{
numberOfLetters--;
}
else if (isdigit(userInput))
printf("please enter only characters:\n");
continue;
}
return numberOfLetters;
}
int printing_average()
{
printf("please enter couple of words:\n");
return printf("the average of number of letters and number of words is: %d", num_of_letters()/num_of_words());
}
To answer your actual question: yes, you can call an arbitrary number of functions as part of a printf call.
If you are wanting to actually count the same set of words for both letters and words, your logic doesn’t work. Each time “getchar()” is called, it takes something out of the input buffer. So for the first calls will read some the input until an EOF is seen. At that point, the second function gets called, and it immediately sees EOF, so there won’t be any letters/words to count.
To solve this, you need to rearrange your code to either:
1. Collect all the input into an array, and then use the two functions to determine how many of each thing there is.
2. Write a new function that calculates both numbers of things in one function.
I prefer option two. It is an easier solution, and doesn’t cause problems if the input is very large – sure, it will take some time, but you don’t need to store everything and then count it twice!