2013-06-21 79 views
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; 
} 
+2

你有问题吗? –

+0

请尝试http://codereview.stackexchange.com/。堆栈溢出意味着明确定义的问题,其他人可以在未来受益。 –

+0

对不起,我的问题是if语句。我得到一个错误,说不能将用户*转换为int *。不知道这是什么意思 – user2204993

回答

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