2017-07-07 244 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'會更有用 –