繁体   English   中英

C ++结构指针

[英]C++ struct pointers

我的代码无法正常工作。 我有一个-fpermissive错误(“ 从'int'到'persona *'[-fpermessive]的无效转换 “)。 你能帮助我吗? 这是我的第一个实际程序,对于错误和英语不好对不起。

    #include <iostream>

using namespace std;

struct persona
{
    char nome[20];
    unsigned int eta;
    unsigned int altezza;
    unsigned int peso;
};

int totale = 0;
struct persona prs[100];

void leggere_dati(persona* prs)
{
    cout << "Persona numero: " << (totale + 1) << endl;
    cout << "Nome: " << prs->nome << endl;
    cout << "Eta': " << prs->eta << endl;
    cout << "Altezza: " << prs->altezza << endl;
    cout << "Peso: " << prs->peso << endl;
    cout << "-----------------------------------------------\n";
}

void inserire_dati(persona* prs)
{
    cout << "Nome? ";
    cin >> prs -> nome;
    cout << "\nEta'? ";
    cin >> prs -> eta;
    cout << "\nAltezza? ";
    cin >> prs -> altezza;
    cout << "\nPeso? ";
    cin >> prs -> peso;
}

int main()
{
     int risposte = 0;
    char risp = 0;

        do{
        inserire_dati(totale);
        cout << "Inserire un'altra persona? (S/N)" << endl;
        cin >> risp;
        if (risp == 'S')
    {
        risposte += 1;
        totale++;
        continue;
    }
    } while (risp == 's' || risp == 'S');

    if (risp == 'n' || risp == 'N')
    {
        for (totale = 0; totale <=  risposte; totale++)
            leggere_dati(totale);
    }
}

您正在致电:

 inserire_dati(totale);

定义为:

void inserire_dati(persona* prs);

虽然总数是:

int totale = 0;

那是明显的错误。 但是背景问题是您没有角色结构的对象来读取数据。据我所知,您的代码应该是:

inserire_dati(&prs[totale]);

您正在该函数中接受指向角色结构的指针,这是正确的,因为您将要修改结构的内容。 totale占据最后一个职位(我认为,但您应无条件增加totale )。 为了获得指向结构的指针,请使用&,并在对象前加上prs [totale]。 由于向量的名称是指向其开头的指针,因此prs + totale也可以接受。 在这种情况下,您将使用可读性较低的指针算法。

另外,我不明白main()的最后一部分。

最后,如果您确实在使用C++ ,则没有真正的理由使用char[]代替string

完整的main()变为:

int main()
{
    char risp = 0;

    do {
        inserire_dati(&prs[totale]);
        ++totale;
        cout << "Inserire un'altra persona? (S/N)" << endl;
        cin >> risp;
    } while (risp == 's' || risp == 'S');

    for(int i = 0; i < totale; ++i) {
         leggere_dati(&prs[totale]);
    }
}

但是,进一步,我看到您正在使用totale作为全局变量。 会将totaleprs包装在一个整体结构中。

struct personas {
    static const int Max = 100;
    struct prs[Max];
    int totale;
};

还有一些其他更改,您可以在IDEOne中找到

希望这可以帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM