![](/img/trans.png)
[英]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.