2016-02-09 154 views
-3

这就是我到目前为止所做的。当我尝试将项目添加到数组时,程序崩溃。我正在寻找它,最终存储该项目,并获取当前时间,并将该项目标记为未完成,直到用户输入“完成”。C++结构和动态分配阵列

不能使用 - 标准集装箱或智能指针

#include <iostream> 
#include <algorithm> 
#include <string> 
#include <iomanip> 
#include <ctime> 
using namespace std; 

struct List{ 
    string items; 
    char completed; 
    int time_t; 

}; 

int main() 
{ 
    // Declare Variables 
    int userChoice = 0; 
    int numItems = 0; 
    int count = 0; 
    List* list = new List[]; 

    // Get current time 
    time_t recordedTime = time(nullptr); 
    tm localTime = *localtime(&recordedTime); 

    // Give the user some options 
    cout << "1. Add Item" << endl; 
    cout << "2. Remove Item" << endl; 
    cout << "3. Sort Items" << endl; 
    cout << "4. Mark as Completed" << endl; 
    cout << "5. Exit" << endl; 
    cout << "Enter the number of the operation you wish to perform: "; 
    cin >> userChoice; 
    cout << endl; 

    // Perform the operation 
    switch(userChoice) 
    { 
    case 1: 
     { 
      cin.ignore(50, '\n'); 
      cout << "Enter one item per line, or enter 'done' to finish\n"; 

     while(true) 
     { 
      do{ 
       count++; 
       cout << "Item" << count << ": "; 
       getline(cin, list[count].items); 
      } 
      while(list[count].items !="done"); 

      if(list[count].items == "done") 
      { 
       break; 
      } 
      } 
     } 
     break; 
    case 2: 
     { 

     } 
     break; 
    case 3: 
     { 

     } 
     break; 
    case 4: 
     { 
      cout << "Item #: "; 
     } 
     break; 
    case 5: 
     { 
      return 0; 
     } 

    } 

    // Output the list 
    cout << "-------Items-------" << endl; 

    cout << "Enter the number of the operation you wish to perform: "; 
    cin >> userChoice; 


    return 0; 
} 
+0

代码中没有数组。 – juanchopanza

+0

您正在使用下标间接指向单个结构的指针。 –

+0

你能详细说明你的代码“不起作用”吗?你在期待什么,究竟发生了什么? **如果您遇到异常或错误,请发布其发生的行和详细信息。**请[编辑]这些详细信息,否则我们可能无法提供帮助。 –

回答

0

我的建议是你应该使用vector包含所有项目。但是这会改变你的代码。

更简单的方法是改变你的列表定义 List* list = new List[1000]; 这将ALLOC数组大小为1000,你以前的定义只是一个页头List,并用指针list指向它。

编辑

,如果你不知道尺寸,你应该使用vector定义名单为vector<List> list,并使用push_back追加项目的容器。

{ 
    cout << "Item" << count << ": "; 
    string str; 
    getline(cin, str); 
    List item {str, 'N', localtime}; 
    list.push_back(move(item)); 
} 

编辑

不能使用STL和记忆唯一的限制,我觉得你有你的List定义更改为LinkedList,像

struct List{ 
    string items; 
    char completed; 
    int time_t; 
    List* next; 
}; 

并在每次输入时分配内存,您必须有另一个指向记忆的指针呃你输入的最后一项。 如果你不使用stl,你将很难排序。

+0

问题是我需要数组来保存无限数量的项目(仅限于内存)。 – bradym55

+0

我没有提到,对于这个特定的项目,我们不能使用任何标准容器,如std :: vector – bradym55

+0

@ bradym55,您将需要根据需要随时调整您的数组大小 –