int count_letters(string text, int length);
int count_words(string text);
int count_sentences(string text);
void final(int letters, int words, int sentences);
int main(void)
{
string text = get_string("Text: \n");
int length = strlen(text);
//printf("%i\n",length);
int letters = count_letters(text, length);
Here I need variable "length" in all these four functions but all these functions already have a string type parameter.Is it possible to pass different types of parameters in a function?
Basically i want to know if this is correct (line 1 and line 13) and if no then how can i use this length variable in all these functions without having to locally define it in each functtion ?
CodePudding user response:
C strings are null character terminated. You do not need to pass the length of the string to the function. You need to iterate until you reach this character
Example:
int count_letters(string text) //better to return size_t
{
int result = 0;
for(int index = 0; text[index] != '\0'; index )
{
if(isalpha((unsigned char)text[index]))
{
result = 1;
}
}
return result;
}
CodePudding user response:
Of course it's possible. You already did it:
int count_letters(string text, int length);
count_letters
has a string
parameter called text
and an int
parameter called length
.
And I'm sure you already know some functions that allow this:
printf("the magic number is %d\n", 42);
// ^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^
// function const char * int