我想写的程序是; 编写一个程序,让用户可以跟踪他们上次与每个朋友交谈的时间。用户应该能够添加新朋友(尽可能多的朋友!)并存储他们上次与每位朋友交谈的天数。让用户更新这个值(但不要让它们输入假值数字,如负值)。这样就可以显示按朋友姓名排序的列表,以及他们与每位朋友交谈后的最近情况。
以下是我到目前为止编写的代码。不确定如何进步。
#include <iostream>
#include <string>
using namespace std;
struct User {
string name;
int noDays;
};
int *growArray (int * friends, int * size) {
*size *= 2;
int *new_friends = new int[*size];
for (int i=0; i < *size; i++) {
new_friends[i] = friends[i];
}
delete [] friends;
return new_friends;
}
int main()
{
User user;
int control;
int next_element = 0;
int size = 10;
int *friends = new int[size];
if (size == next_element+1) {
friends = growArray(friends, &size);
}
for (int i = 0; i < size; i++) {
cout << "Please enter your friends name" << endl;
cin >> user.name;
cout << "Please enter no of days you last spoke to them" << endl;
cin >> user.noDays;
next_element++;
}
return 0;
}
答案 0 :(得分:0)
我在上面重写了这段代码,你可以引用它(//为了改变):
#include <iostream>
#include <string>
using namespace std;
struct User {
string name;
int noDays;
};
//Note: Return Types
User *growArray (User * friends, int * size) {
//cout << "into growArray()\n";
User *new_friends = new User[*size * 2];
for (int i=0; i < *size; i++) {
new_friends[i].name = friends[i].name;
new_friends[i].noDays = friends[i].noDays;
}
*size *= 2; //Place here
delete [] friends;
return new_friends;
}
int main()
{
int size = 2;
int next_element = 0;
//struct array
User *friends = new User[size];
//use while instead of for
while(1)
{
cout << "Please enter your friend's name (or q to exit):" << endl;
cin >> friends[next_element].name;
if (friends[next_element].name == "q")
{
break;
}
cout << "Please enter no of days you last spoke to them:" << endl;
cin >> friends[next_element].noDays;
if (size == ++next_element)
{
//Return Types
friends = growArray(friends, &size);
}
}
//print result
cout << "Do you want to print this list? (Y/N)";
string choice;
if (((cin >> choice) == "Y") || choice =="y")
{
cout << "List:\n";
for (int i = 0; i < next_element; i++)
{
cout << friends[i].name << '\t' << friends[i].noDays << '\n';
}
}
//delete
delete [] friends;
return 0;
}