0

我正在尝试编写的程序是;编写一个程序,让用户跟踪他们上次与每个朋友交谈的时间。用户应该能够添加新朋友(想多少就加多少!)并存储他们上次与每个朋友交谈的天数。让用户更新这个值(但不要让他们输入像负值这样的虚假数字)。可以显示按朋友姓名排序的列表,按他们与每个朋友交谈的最近时间。

以下是我到目前为止编写的代码。不太确定如何进步。

#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;
}
4

1 回答 1

0

上面这段代码我重写了,大家可以参考一下(//for changed):

#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;   
}
于 2015-03-16T03:17:57.870 回答