简体   繁体   English

如何使用 char* 从用户那里获取数据,然后在 C++ 中执行输入数据的深度复制?

[英]How do I take data from user using char* and then performs deep copy of entered data in C++?

Take data from user in runtime from char*从 char* 中获取用户在运行时的数据

You should be using std::string , which performs all the data lifetime management and deep copy for you.您应该使用std::string ,它为您执行所有数据生命周期管理和深层复制。

In turn, that makes the Student class's destructor, default constructor, copy constructor all just do the right thing .反过来,这使得Student类的析构函数、默认构造函数、复制构造函数都只做正确的事情 Also the assignment operator will just do the right thing , but that's not exercised in the main routine.此外,赋值运算符只会做正确的事情,但在main例程中不会执行。

In the code, I used = default on the destructor, default constructor, and copy constructor to highlight that the default compiler generated routines are good.在代码中,我在析构函数、默认构造函数和复制构造函数上使用了= default以强调默认编译器生成的例程是好的。

A couple of improvements would be for Getinfo() to be Getinfo(istream& in, ostream& out) , and for show() to be show(ostream& out) .一些改进是将Getinfo()变为Getinfo(istream& in, ostream& out)并将show()变为show(ostream& out)

#include <iostream>
#include <stdexcept>
#include <string>

using std::cin;
using std::cout;
using std::istream;
using std::runtime_error;
using std::stof;
using std::stoi;
using std::string;

static auto get_string(istream&) -> string;
static auto get_int(istream&) -> int;
static auto get_float(istream&) -> float;

class Student final {
    string name;
    int age = 0;
    float gpa = 0.0f;
public:
    ~Student() = default;
    Student() = default;
    Student(string n, int a, float g) : name{move(n)}, age(a), gpa(g) { }
    Student(Student const&) = default;

    void Getinfo() {
        cout << "Enter your name: ";
        name = get_string(cin);
        cout << "Enter your age: ";
        age = get_int(cin);
        cout << "Enter your GPA: ";
        gpa = get_float(cin);
    }

    void show() {
        cout << "Name: " << name << "\n"
            << "Age: " << age << "\n"
            << "GPA: " << gpa << "\n";
    }
};

int main() {
    Student s1;
    s1.Getinfo();
    s1.show();
    Student s2 = s1;
    s2.show();
    Student s3(s2);
    s3.show();
}

auto get_string(istream& in) -> string {
    string line;

    if (getline(in, line)) {
        return line;
    }

    throw runtime_error("get_string");
}

auto get_int(istream& in) -> int {
    string line;

    if (getline(in, line)) {
        return stoi(line);
    }

    throw runtime_error("get_int");
}

auto get_float(istream& in) -> float {
    string line;

    if (getline(in, line)) {
        return stof(line);
    }

    throw runtime_error("get_float");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM