Search code examples
cfunctionstructreturn-valuecs50

How to output two values from the same function


Basically what the title says. I have this program:

#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>

int letter_countf(string Text1);

int main(void)
{
    string TextIn = get_string("Text: ");
    int letter_count = letter_countf(TextIn);
    printf("%i\n", letter_count);

}

int letter_countf(string Text)
{
    int Is_letter = 0; int Is_space = 0;
    for(int i = 0; i < strlen(Text); i++)
    {
        if (isspace(Text[i]) != 0)
        {
            Is_space++;
        }
        else
        {
            Is_letter++;
        }
    }
}

And I want the output of the function letter_countf, to be both the Is_space and Is_letter variables. How do I store both values?


Solution

  • There are different ways. For example you can declare a structure and return an object of this structure as for example

    struct Items
    {
        int letter;
        int space;
    };
    
    struct Items letter_countf(string Text)
    {
        struct Items items = { .letter = 0, .space = 0 };
    
        for(int i = 0; i < strlen(Text); i++)
        {
            if (isspace(Text[i]) != 0)
            {
                items.space++;
            }
            else
            {
                items.letter++;
            }
        }
    
        return items;
    }
    

    Another way is declare the variables letter_count and space_count in main and pass them to the function by reference

    void letter_countf(string Text, int *letter_count, int *space_count );
    
    //...
    
    int letter_count = 0, space_count = 0;
    letter_countf( TextIn, &letter_count, &space_count );