我尝试使用带指针的动态内存分配来打印一个字符数组。如果我评论一个pf变量工作,但当我试图打印两个程序停止。
这是主要的CPP。
#include <iostream>
#include "ContactInfo.h"
using namespace std;
int main() {
int n = 0;
char *ph, *nm;
ContactInfo *allcontacts;
cout << "How many people you want to add to phone book? ";
cin >> n;
allcontacts = new ContactInfo[n];
for (int i=0; i < n; i++) {
cout << i + 1 << ") Name: ";
cin >> nm;
allcontacts[i].setName(nm);
cout << i + 1 << ") Phone: ";
cin >> ph;
allcontacts[i].setPhone(ph);
}
cout << setw(8) <<"Name" << setw(8) << "Phone\n";
cout << "------------------------------------------------------\n";
for (int i=0; i < n; i++){
allcontacts[i].display();
}
return 0;
}
CPP
#include "ContactInfo.h"
void ContactInfo::setName(char *n) {
name = new char[strlen(n) + 1];
strcpy(name, n);
}
void ContactInfo::setPhone(char *p) {
phone = new char[strlen(p) + 1];
strcpy(phone, p);
}
ContactInfo::ContactInfo() {
// setName("");
// setPhone("");
}
ContactInfo::ContactInfo(char *n, char *p) {
setName(n);
setPhone(p);
}
ContactInfo::~ContactInfo() {
delete [] name;
delete [] phone;
name = nullptr;
phone = nullptr;
}
const char *ContactInfo::getName() const {
return name;
}
void ContactInfo::display() const {
cout << getName();
cout << getPhoneNumber();
cout << endl;
}
const char *ContactInfo::getPhoneNumber() const {
return phone;
}
HEADER
#include <iostream>
#include <cstring> // Needed for strlen and strcpy
using namespace std;
// ContactInfo class declaration.
class ContactInfo
{
private:
char *name; // The contact's name
char *phone; // The contact's phone number
public:
ContactInfo(char *, char *);
ContactInfo();
void setName(char *);
void setPhone(char *);
~ContactInfo();
const char *getName() const;
const char *getPhoneNumber() const;
void display() const;
};
输出继电器
您想为电话簿添加多少人? 2
1)姓名:www
1)电话:22
处理完成,退出代码为0
答案 0 :(得分:1)
您正在将C和C ++代码混合在一起。您必须使用std::string
作为输入,而不是char*
。请尝试以下代码:
#include <iostream>
#include <vector>
#include <string>
#include <iomanip>
class ContactInfo {
private:
std::string name;
std::string phone;
public:
ContactInfo() {
}
ContactInfo(const std::string &Name, const std::string &Phone) {
name = Name;
phone = Phone;
}
void display() const {
std::cout << name << " " << phone << std::endl;
}
};
int main() {
int n = 0;
std::cout << "How many people you want to add to phone book? ";
std::cin >> n; std::cin.get();
std::vector<ContactInfo> all_contacts;
for (int i = 0; i < n; i++) {
std::string name, phone;
std::cout << i + 1 << ") Name: ";
std::cin >> name;
std::cout << i + 1 << ") Phone: ";
std::cin >> phone;
all_contacts.push_back(ContactInfo(name, phone));
}
std::cout << std::setw(8) << "Name" << std::setw(8) << "Phone" << std::endl;
std::cout << "------------------------------------------------------" << std::endl;
for (auto i : all_contacts) {
i.display();
}
return 0;
}