[英]How do I take input from user as a password and compare it with the data in the file in c++
[英]How do I take data from user using char* and then performs deep copy of entered data in C++?
您应该使用std::string
,它为您执行所有数据生命周期管理和深层复制。
反过来,这使得Student
类的析构函数、默认构造函数、复制构造函数都只做正确的事情。 此外,赋值运算符只会做正确的事情,但在main
例程中不会执行。
在代码中,我在析构函数、默认构造函数和复制构造函数上使用了= default
以强调默认编译器生成的例程是好的。
一些改进是将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.