我的代码不工作。我有一个错误 -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;
这是明显的错误。但是背景问题是您没有persona 结构的对象来读取数据。据我了解您的代码,该行应该是:
inserire_dati(&prs[totale]);
您在该函数中接受了指向 persona 结构的指针,这是正确的,因为您要修改该结构的内容。 totale 保留最后一个位置(我认为,但你应该无条件地增加 totale)。为了获得指向您使用 & 的结构的指针,前面是对象,即 prs[totale]。由于 vector 的名称是指向其开头的指针,因此 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 作为全局变量。我会将 totale 和 prs 包装在一个完整的结构中。
struct personas {
static const int Max = 100;
struct prs[Max];
int totale;
};
还有其他一些changes which you can find in IDEOne .
希望这对您有所帮助。
关于C++ 结构指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44967703/