2017-07-07 249 views
0

我的代码不工作。我有一个错误-fpermissive(“从'int'无效转换为'persona *'[-fpermessive]”)。 你能帮我吗?这是我第一个真正的程序,对于错误和糟糕的英语感到抱歉。C++结构指针

#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); 
    } 
} 
+0

变量'totale',它是什么类型?为什么试图将它作为参数传递给'inserire_dati'?你是否想通过例如'&PRS [驻颜]'? –

+0

您应该告诉读者_where_发生错误,即包含完整的错误文本,其中应包含行号。值得注意的 –

回答

2

要调用:

inserire_dati(totale); 

定义为:

void inserire_dati(persona* prs); 

虽然驻颜是:

int totale = 0; 

这是明显的错误。但背景的问题是,你没有人物结构的对象读取数据正如我理解你的代码,该行应该是:

inserire_dati(&prs[totale]); 

您接受的指针persona该功能中的结构,这是正确的,因为您要修改结构的内容。 totale占据了最后的位置(我认为,但你应该无条件地增加总计)。为了得到一个指向你使用&的结构的指针,在对象之前是prs [totale]。由于矢量的名称是指向其开始的指针,因此prs + totale也是可以接受的。在那种情况下,你会使用指针算术,这是不太可读的。

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

最后,如果你真的使用C++,存在使用替代char[]没有真正的理由。

完整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]); 
    } 
} 

但是,好了,进一步让我看到你正在使用驻颜为全局变量。我会在整个结构中包装总计prs

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

和其他几个changes which you can find in IDEOne

希望这会有所帮助。

+1

是使用适当的容器,如std :: vector和std :: string。 –

+1

@TheTechel有时你不需要拥有动态内存,就像载体一样。 (因此,我同意std :: string在这段代码中会有很大的改进)。如果你只需要100人,那么这个阵列就好了。 – Shirkam

+1

@Shirkam但如果你经常少于100人,分配更多是浪费。有多少实际程序只需要固定数量的对象?即使他们有一个最大值,通过分配一个固定长度有多少浪费空间?这种模式看起来像是由初学者通过教程教授的,就好像他们需要另一种在现实世界中几乎没有用处的东西。 IME固定长度数组的有用的例子是缓冲区组成C的字符串,与硬件的接口等。这些情况相当罕见。对于任意对象来说,这似乎几乎没有用处。学习'std :: vector'会更有用 –