2017-09-22 61 views
-4

我必須編寫一個提示輸入姓名,年齡和工資(String,Int和Float)的程序。所有這些都必須存儲到指針變量中。然後輸出值和指針地址。我不確定如何存儲用戶輸入。 >>對於cin有錯誤'沒有操作符>> >>「匹配這些操作數」。如何正確存儲用戶輸入而不出錯?如何將用戶輸入存儲到指針變量中?

#include "stdafx.h" 
#include <iostream> 

using namespace std; 

int main() 
{ 
int *Age = nullptr; 
string *Name = nullptr; 
float *Salary = nullptr; 
cout << "What is your name? \n"; 
cin >> *Name; 
cout << "Name- " << Name << " Pointer Address- " << &Name << endl; 
cout << "What is your age?\n"; 
cin >> Age; 
cout << "Age- " << Age << " Pointer Address- " << &Age << endl; 
cout << "What is your salary?\n"; 
cin >> Salary; 
cout << "Salary- " << Salary << " Pointer Address- " << &Salary << endl; 
return 0; 
} 
+3

這應該在任何教科書或在線教程的指針部分的第一頁。 – John3136

+0

答案很簡單:根本不要使用原始指針。 – user0042

回答

1
#include <iostream> 
using namespace std; 

int main() 
{ 
    int *Age = new int; 
    string *Name = new string; 
    float *Salary = new float; 
    cout << "What is your name? \n"; 
    cin >> *Name; 
    cout << "Name- " << *Name << " Pointer Address- " << Name << endl; 
    cout << "What is your age?\n"; 
    cin >> *Age; 
    cout << "Age- " << *Age << " Pointer Address- " << Age << endl; 
    cout << "What is your salary?\n"; 
    cin >> *Salary; 
    cout << "Salary- " << *Salary << " Pointer Address- " << Salary << endl; 
    delete Name; 
    delete Age; 
    delete Salary; 

    return 0; 
} 
  1. 要初始化這些指針,然後再在值讀取,你可以不讀入nullptr

  2. 你要提領他們當你打印出來

  3. 一旦完成使用,您應該刪除指針

+0

雖然這回答了這個問題,但是這個代碼從不「刪除」指針,因此泄漏。 (理想情況下,這將與智能指針) – Bitwize

+0

@Bitwize修正,謝謝指出 –

相關問題