Задание: сделать массив из структур(содержание структуры это информация про ваших друзей, имя фамилия и т.д.). При желании пользователя пополнять список. Код ниже компилируется, но вот при выполнении какая-то лажа и если честно я в замешательстве.
#include <iostream>
#include <cstring>
using namespace std;
struct pBook
{
char name[100];
char surname[100];
char adress[100];
char pNumber[100];
}*PhoneBook;
void init(pBook *a, int &size);
void addData(pBook*a, int size);
pBook* add(pBook *a, int &size);
void showFriendList(pBook *a, int size);
void main()
{
int size = 1;
PhoneBook = new pBook[size];
init(PhoneBook, size);
cout << "Your frined list." << endl << endl;
showFriendList(PhoneBook, size);
cout << "\n\nInfo about Oksana." << endl << endl;
aboutOksana(PhoneBook, size);
delete[]PhoneBook;
cin.get();
cin.get();
}
void init(pBook *a, int &size)
{
char s;
do {
addData(a, size);
cout << "Wanna add new friend?\ny/n\n";
cin >> s;
cin.ignore();
if (s == 'y') a = add(a, size);
} while (s == 'y');
}
void addData(pBook*a, int size)
{
cout << "Enter name: ";
gets_s(a[size - 1].name, 100);
cout << "Enter surname: ";
gets_s(a[size - 1].surname, 100);
cout << "Enter adress: ";
gets_s(a[size - 1].adress, 100);
cout << "Enter phone-number: ";
gets_s(a[size - 1].pNumber, 100);
}
pBook* add(pBook *a, int &size)
{
pBook *temp = new pBook[size];
for (int i = 0; i < size; ++i) {
strcpy_s(temp[i].name, strlen(a[i].name) + 1, a[i].name);
strcpy_s(temp[i].surname, strlen(a[i].surname) + 1, a[i].surname);
strcpy_s(temp[i].adress, strlen(a[i].adress) + 1, a[i].adress);
strcpy_s(temp[i].pNumber, strlen(a[i].pNumber) + 1, a[i].pNumber);
}
delete[]a;
size++;
a = new pBook[size];
for (int i = 0; i < size - 1; ++i) {
strcpy_s(a[i].name, strlen(temp[i].name) + 1, temp[i].name);
strcpy_s(a[i].surname, strlen(temp[i].surname) + 1, temp[i].surname);
strcpy_s(a[i].adress, strlen(temp[i].adress) + 1, temp[i].adress);
strcpy_s(a[i].pNumber, strlen(temp[i].pNumber) + 1, temp[i].pNumber);
}
delete[]temp;
return a;
}
void showFriendList(pBook *a, int size)
{
for (int i = 0; i < size; ++i) {
cout << i + 1 << ". ";
cout << "Name = " << a[i].name << endl;
cout << "Surname = " << a[i].surname << endl;
cout << "Adress = " << a[i].adress << endl;
cout << "Phone-number = " << a[i].pNumber << endl;
cout << endl;
}
}
Путём усилий и труда я нашёл косяк, просто функции возвращают теперь указатель на наш массив. Вот рабочее решение моего кода(мб оно не совсем оптимальное, но рабочее).
#include <iostream>
#include <cstring>
using namespace std;
struct pBook
{
char name[100];
char surname[100];
char adress[100];
char pNumber[100];
}*PhoneBook;
pBook* init(pBook *a, int &size);
pBook* addData(pBook*a, int size);
pBook* add(pBook *a, int &size);
void showFriendList(pBook *a, int size);
void aboutOksana(pBook *a, int size);
void main()
{
int size = 1;
PhoneBook = new pBook[size];
PhoneBook = init(PhoneBook, size);
cout << "Your frined list." << endl << endl;
showFriendList(PhoneBook, size);
cout << "\n\nInfo about Oksana." << endl << endl;
aboutOksana(PhoneBook, size);
delete[]PhoneBook;
cin.get();
cin.get();
}
pBook* init(pBook *a, int &size)
{
char s;
do {
a = addData(a, size);
cout << "Wanna add new friend?\ny/n\n";
cin >> s;
cin.ignore();
if (s == 'y') a = add(a, size);
} while (s == 'y');
return a;
}
pBook* addData(pBook*a, int size)
{
cout << "Enter name: ";
gets_s(a[size - 1].name, 100);
cout << "Enter surname: ";
gets_s(a[size - 1].surname, 100);
cout << "Enter adress: ";
gets_s(a[size - 1].adress, 100);
cout << "Enter phone-number: ";
gets_s(a[size - 1].pNumber, 100);
return a;
}
pBook* add(pBook *a, int &size)
{
pBook *temp = new pBook[size];
for (int i = 0; i < size; ++i) {
strcpy_s(temp[i].name, strlen(a[i].name) + 1, a[i].name);
strcpy_s(temp[i].surname, strlen(a[i].surname) + 1, a[i].surname);
strcpy_s(temp[i].adress, strlen(a[i].adress) + 1, a[i].adress);
strcpy_s(temp[i].pNumber, strlen(a[i].pNumber) + 1, a[i].pNumber);
}
delete[]a;
size++;
a = new pBook[size];
for (int i = 0; i < size - 1; ++i) {
strcpy_s(a[i].name, strlen(temp[i].name) + 1, temp[i].name);
strcpy_s(a[i].surname, strlen(temp[i].surname) + 1, temp[i].surname);
strcpy_s(a[i].adress, strlen(temp[i].adress) + 1, temp[i].adress);
strcpy_s(a[i].pNumber, strlen(temp[i].pNumber) + 1, temp[i].pNumber);
}
delete[]temp;
return a;
}
void showFriendList(pBook *a, int size)
{
for (int i = 0; i < size; ++i) {
cout << i + 1 << ". ";
cout << "Name = " << a[i].name << endl;
cout << "Surname = " << a[i].surname << endl;
cout << "Adress = " << a[i].adress << endl;
cout << "Phone-number = " << a[i].pNumber << endl;
cout << endl;
}
}
void aboutOksana(pBook *a, int size)
{
for (int i = 0; i < size; ++i) {
if (strcmp(a[i].name, "Oksana") == 0) {
cout << "Info about " << a[i].name << " " << a[i].surname << endl;
cout << "Name = " << a[i].name << endl;
cout << "Surname = " << a[i].surname << endl;
cout << "Adress = " << a[i].adress << endl;
cout << "Phone-number = " << a[i].pNumber << endl;
cout << endl;
}
}
}
Я бы несколько рефакторизовал вашу программу (часть с Оксаной опущена) - если оставаться в рамках обычного C с выводом через cout (по сути, это единственное, что отличает вашу программу от программы на C) - для начала до
#include <iostream>
#include <cstring>
using namespace std;
struct pBook
{
char name [100];
char surname[100];
char adress [100];
char pNumber[100];
};
void fill(pBook*&a, int &size);
void addData(pBook*&a, int &size);
void showFriendList(pBook *a, int size);
int main()
{
pBook* PhoneBook = nullptr;
int PhoneBookSize = 0;
fill(PhoneBook, PhoneBookSize);
cout << "Your frined list." << endl << endl;
showFriendList(PhoneBook, PhoneBookSize);
//cout << "\n\nInfo about Oksana." << endl << endl;
//aboutOksana(PhoneBook, size);
delete[] PhoneBook;
cin.get();
}
void fill(pBook*&a, int &size)
{
for(char s = 'y'; s == 'y'; (cin >> s).ignore())
{
addData(a,size);
cout << "Wanna add new friend?\ny/n\n";
};
}
void readString(const char * prompt, char * field, int size = 100)
{
cout << "Enter " << prompt << ": ";
gets_s(field, size);
}
void addData(pBook*&a, int& size)
{
pBook *temp = new pBook[size+1];
if (a) memcpy(temp,a,sizeof(pBook)*size);
delete[] a;
a = temp;
readString("name", a[size].name);
readString("surname", a[size].surname);
readString("address", a[size].adress);
readString("phone-number",a[size].pNumber);
++size;
}
void showFriendList(pBook *a, int size)
{
for (int i = 0; i < size; ++i) {
cout << i + 1 << ". ";
cout << "Name = " << a[i].name << endl;
cout << "Surname = " << a[i].surname << endl;
cout << "Adress = " << a[i].adress << endl;
cout << "Phone-number = " << a[i].pNumber << endl;
cout << endl;
}
}
По крайней мере от двойной пересылки всей памяти туда-назад при добавлении одной записи точно надо избавляться.... Следующим шагом я бы прибавлял не один элемент, а удваивал размер зарезервированного массива.
Вот как мне представляется этот код на C++ (естественно, разных решений может быть масса):
#include <iostream>
#include <string>
#include <set>
using namespace std;
class PBook
{
string name, surname, address, phone;
public:
PBook(const char * name = ""):name(name){}
friend ostream& operator << (ostream&, const PBook&);
friend istream& operator >> (istream&, PBook&);
friend bool operator < (const PBook& a, const PBook& b) { return a.name < b.name; }
};
ostream& operator << (ostream&os, const PBook&p)
{
os << "Name: " << p.name << endl;
os << "Surname: " << p.surname << endl;
os << "Address: " << p.address << endl;
os << "Phone: " << p.phone << endl;
return os;
}
istream& operator >> (istream& is, PBook& p)
{
cout << "Name: "; getline(is,p.name);
cout << "Surname: "; getline(is,p.surname);
cout << "Address: "; getline(is,p.address);
cout << "Phone: "; getline(is,p.phone);
return is;
}
int main()
{
multiset<PBook> pb;
for(char s = 'y'; s == 'y'; (cin >> s).ignore())
{
PBook p; cin >> p; pb.insert(p);
cout << "Wanna add new friend (y/n)? ";
};
cout << "-----------\nYour frined list:\n";
for(auto p: pb) cout << p << endl;
cout << "-----------\nYour Oksana list:\n";
auto ox = pb.equal_range("Oksana");
for(auto it = ox.first; it != ox.second; ++it)
cout << *it << endl;
cin.get();
}
Сборка персонального компьютера от Artline: умный выбор для современных пользователей