如何将用户输入存储到指针变量中?

时间:2017-09-22 00:31:35

标签: c++ pointers

我必须编写一个程序,提示输入名称,年龄和工资(String,Int和Float)。其中所有这些都必须存储到指针变量中。然后输出值和指针地址。我不确定如何存储用户输入。 >>因为cin有错误'no operator'>>“匹配这些操作数'。如何正确存储用户输入而没有任何错误?

#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;
}

1 个答案:

答案 0 :(得分: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. 完成使用后,您应该删除指针