男性和女性的结构

Structure of Males and Females

本文关键字:结构      更新时间:2023-10-16

我应该使用数组a[10],其元素类型为struct osoba,输入10个姓名和性别,其中姓名为…然后我应该使用函数void brosoba来确定有多少男性和女性(我输入了多少),我唯一的问题是如何调用该函数来开始工作,因为教授坚持在void函数中使用指针,同时使用数组…(

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
struct osoba 
{
    char naziv[30];
    char pol[30];
}a[10];
 void brosoba(osoba *x[])
 {

    int Zene=0,Muskarci=0;
        for(int i=0;i<10;i++)
    {
        if(*x[i]-> pol=='z')Zene++;
        if(*x[i]->pol=='m')Muskarci++;
    }
    printf("Muskaraca ima:%dn Zena ima:%dn",Muskarci,Zene);
 }
 int main()
 {
    int i;
    for(i=0;i<10;i++)
    {
        printf("Unesi ime osobe %dn",i);
        gets(a[i].naziv);
        while(getchar()!='n');
        printf("Unesi pol osobe %d(m/z)n",i);
        gets(a[i].pol);
        while(getchar()!='n');
    }
      brosoba();
     return 0;
 }

这是我对标准c++的看法,而不是C

#include <algorithm>
#include <iostream>
#include <stdexcept>
#include <string>
#include <vector>
enum class gender_t { male, female, other };
struct osoba
{
    std::string name;
    gender_t gender;
};
static inline gender_t to_gender(char input)
{
    switch(input)
    {
        case 'm': case 'M': return gender_t::male;
        case 'f': case 'F': return gender_t::female;
        case 'o': case 'O': case '*': case '?': return gender_t::other;
    }
    throw std::runtime_error("Unknown gender specification");
}
void brosoba(std::vector<osoba> x)
{
    auto pred = [](gender_t g, osoba const& o) { return g == o.gender; };
    using namespace std::placeholders;
    std::cout << "Male: "   << std::count_if(x.begin(), x.end(), std::bind(pred, gender_t::male,   _1)) << ", "
              << "Female: " << std::count_if(x.begin(), x.end(), std::bind(pred, gender_t::female, _1)) << ", "
              << "Other: "  << std::count_if(x.begin(), x.end(), std::bind(pred, gender_t::other,  _1)) << "n";
}
int main()
{
    std::vector<osoba> a;
    std::string name;
    char gender;
    while (std::cin >> name >> gender)
        a.push_back({name, to_gender(gender)});
    brosoba(a);
}

查看Live on Coliru

输入

mike m
thomas m
elayne f
puck o
hector o
troy m
olly f

打印输出
Male: 3, Female: 2, Other: 2

或者,一个解决方案,让它保持开放的性别可以指定:

struct osoba
{
    std::string name;
    char gender;
};
void brosoba(std::vector<osoba> const& xs)
{
    std::map<char, size_t> histo;
    for(auto& x : xs)
        histo[x.gender]++;
    for (auto& entry: histo)
        std::cout << entry.first <<  ": " << entry.second << "n";
}
int main()
{
    std::vector<osoba> a;
    std::string name;
    char gender;
    while (std::cin >> name >> gender)
        a.push_back({name, gender});
    brosoba(a);
}

现在打印(Live on Coliru):

f: 2
m: 3
o: 2

我将function声明为:

void brosoba(struct osoba * x)

同样,您调用它时不传递参数。你可以试试:

brosoba( a );

这将传递指向a的第一个元素的指针,类型为struct osoba *。然后,由于该数组的每个元素都是对象,而不是指针,因此您应该使用.读取字段,而不是->

此外,您正在将char (a[i].pol)数组与char进行比较-单引号表示字符字面量,而双引号表示以空结尾的字符数组,因此这是另一件需要修复的事情。