C++ 使用C+;中的字符指针将字符串保存到类属性+;

C++ 使用C+;中的字符指针将字符串保存到类属性+;,c++,pointers,io,C++,Pointers,Io,我很难使用cin接收输入,将它们保存到几个变量中,然后构造一个类。当我输入第一个输入,而不是等待下一个输入,程序无限循环,并不断显示提示一遍又一遍 课程为: class person { public: char *name; char *email; int phone; // constructor that uses the parameters to initialize the class properties person(char *cNam

我很难使用cin接收输入,将它们保存到几个变量中,然后构造一个类。当我输入第一个输入,而不是等待下一个输入,程序无限循环,并不断显示提示一遍又一遍

课程为:

class person {
public:
    char *name;
    char *email;
    int phone;
    // constructor that uses the parameters to initialize the class properties
    person(char *cName, char *cEmail, int iPhone) {
        name = new (char[32]);  // acquiring memory for storing name
        email = new (char[32]);     // acquiring memory for storing email
        strcpy(name, cName);        // initialize name
        strcpy(email, cEmail);  // initialize email
        phone = iPhone;         // initialize phone
    }
    virtual ~person() {
        delete[] name;
        delete[] email;
    }
};
输入和构造函数调用如下所示:

char* nameIn = new (char[32]);  // acquiring memory for storing name
char* emailIn = new (char[32]);
int iPhoneIn;

cout << "Enter name, email, and phone:\n";

    cin >> *nameIn;
    cin >> *emailIn;
    cin >> iPhoneIn;

person* newPerson = new person(nameIn, emailIn, iPhoneIn); //create node
char*nameIn=new(char[32]);//获取用于存储名称的内存
char*emailIn=new(char[32]);
intiphonein;
cout>*nameIn;
cin>>*电子邮件地址;
cin>>iPhoneIn;
person*newPerson=新人(nameIn、emailIn、iPhoneIn)//创建节点

您可以通过几种方式修复/改进代码

首先,我们将从明显错误的开始。从cin读取输入时,不要取消引用(调用*运算符)字符指针(char*)。cin应接收字符*,而不是字符。如果您向它传递一个字符,它将只写入您输入的第一个字符。因此,如果要输入字符串,需要向其传递一个字符*

cin >> *nameIn; // this should be: cin >> nameIn;
cin >> *emailIn; // this should be cin >> emailIn;
运行此代码段(有或没有建议的更改)以了解我的意思:

#include <iostream>
using namespace std;
int main()  {
    cout << "Input a string: ";
    char * c = new(char[200]);
    cin >> *c; // only writes the first input character. Change to: cin >> c;
    cout << "You input: " << c; // prints the first input character then garbage
    delete[](c);
    return 0;
}

这样既可以运行得更快,又可以省去释放已分配内存的痛苦。您将能够完全删除析构函数。

您应该使用
std::string
而不是C样式的字符串。检查这一个(类似):我将使用它,但是,这个任务的要点是让我们从C到C++过渡,不幸的是,它要求人构造函数取字符指针而不是仅仅使用字符串。那个链接正是我想要的。但是我很难理解为什么我们把cin放在指针中而不是放在延迟指针中。现在,nameIn和emailIn只是指向这些新字符数组的指针。我们不想取消对指针的引用,以便将输入保存到字符数组中吗?编辑:想清楚了,我现在明白了。谢谢大家!
char *name; // change to char name[32];
char *email; // change to char email[32];