2016-02-06 3 views
2

Это то, что у меня есть до сих пор. Я пытаюсь редактировать динамически выделенный массив на C++, однако, когда цикл for работает, он пропускает первый элемент. Мне нужно это, чтобы получить все предметы. Любая помощь приветствуется. Заранее спасибо.Динамическое распределение строковых массивов

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


int main() 
{ 
    // Declare Variables 
    int userChoice = 0; 
    int numItems = 0; 

    cout << "How many items will be on your list? "; 
    cin >> numItems; 

    string *list = new string[numItems]; 

    // Give the user some options 
    cout << "1. Add Item" << endl; 
    cout << "2. Remove Item" << endl; 
    cout << "3. Sort Items" << endl; 
    cout << "4. 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.clear(); // Remove new line from cin 

      for(int i = 0; i < numItems; i++) 
      { 
       cout << "Item #" << i + 1 << " --> "; 
       getline(cin, list[i]); 
      } 
     } 
     break; 
    case 2: 
     { 

     } 
     break; 
    case 3: 
     { 

     } 
     break; 
    case 4: 
     { 
      return 0; 
     } 
    default: 
     { 
      cout << "Error! Invalid Selection" << endl; 
     } 

    } 

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

    // free memory 
    delete [] list; 

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


    return 0; 
} 

ответ

2

Цикл for не пропускает первый элемент. Первый элемент - это просто пустая строка.

Потому что следующие clears ошибки флаги.

cin.clear(); // Remove new line from cin --> No!!!! 

Если вы хотите, чтобы пропустить до новой линии, которую вы должны использовать ignore() вместо этого.

cin.ignore(numeric_limits<streamsize>::max(), '\n'); // this removes until newline from cin ! 
3

Это кажется странным для меня, чтобы быть с использованием STL для некоторых вещей (например, строка), а затем использовать стандартный массив для хранения строк. Кроме того, list является стандартным типом объекта в STL, поэтому это не отличное имя для переменной. Этот исправленный код исправляет ваши проблемы, игнорируя первую строку, а также использует vector вместо new и delete.

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

int main() 
    { 
    // Declare Variables 
    int userChoice = 0; 
    int numItems = 0; 

    cout << "How many items will be on your myList? "; 
    cin >> numItems; 
    cin.ignore(); 

    vector<string> myList; 

    while (true) 
    { 
    // Give the user some options 
    cout << "1. Add Item" << endl; 
    cout << "2. Remove Item" << endl; 
    cout << "3. Sort Items" << endl; 
    cout << "4. Exit" << endl; 
    cout << "Enter the number of the operation you wish to perform: "; 
    cin >> userChoice; 
    cin.ignore(); 
    cout << endl; 

    // Perform the operation 
    switch(userChoice) 
    { 
    case 1: 
     { 
     for(int i = 0; i < numItems; i++) 
      { 
      cout << "Item #" << i + 1 << " --> "; 
      string s; 
      getline(cin, s); 
      myList.push_back (s); 
      } 
     } 
     break; 
    case 2: 
     { 

     } 
     break; 
    case 3: 
     { 
     sort (myList.begin(), myList.end()); 
     } 
     break; 
    case 4: 
     { 
      return 0; 
     } 
    default: 
     { 
      cout << "Error! Invalid Selection" << endl; 
     } 

    } 

    // Output the myList 
    cout << "-------Items-------" << endl; 
    copy(myList.begin(), myList.end(), ostream_iterator<string>(cout, "\n")); 

    } // end of while 
} 

Описание проекта явно говорит, что я не могу использовать стандартные контейнеры, сортировки функции, или смарт-указатели

Redone ниже, чтобы не использовать эти вещи. :)

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

int myCompare (const void * a, const void * b) 
    { 

    if ((*(string *) a) < *(string *) b) return -1; 
    if ((*(string *) a) > *(string *) b) return 1; 
    return 0; 
    } 

int main() 
    { 
    // Declare Variables 
    int userChoice = 0; 
    int numItems = 0; 

    cout << "How many items will be on your myList? "; 
    cin >> numItems; 
    cin.ignore(); 

    string *myList = new string[numItems]; 

    while (true) 
    { 
    // Give the user some options 
    cout << "1. Add Item" << endl; 
    cout << "2. Remove Item" << endl; 
    cout << "3. Sort Items" << endl; 
    cout << "4. Exit" << endl; 
    cout << "Enter the number of the operation you wish to perform: "; 
    cin >> userChoice; 
    cin.ignore(); 
    cout << endl; 

    // Perform the operation 
    switch(userChoice) 
    { 
    case 1: 
     { 
     for(int i = 0; i < numItems; i++) 
      { 
      cout << "Item #" << i + 1 << " --> "; 
      getline(cin, myList [i]); 
      } 
     } 
     break; 
    case 2: 
     { 

     } 
     break; 
    case 3: 
     { 
     qsort (myList, numItems, sizeof (string *), myCompare); 
     } 
     break; 
    case 4: 
     { 
      delete [] myList; 
      return 0; 
     } 
    default: 
     { 
      cout << "Error! Invalid Selection" << endl; 
     } 

    } 

    // Output the myList 
    cout << "-------Items-------" << endl; 
    for(int i = 0; i < numItems; i++) 
     cout << myList [i] << endl; 

    } // end of while 
} 
+0

Это замечательно, и я бы это сделал, но я, вероятно, должен был быть более конкретным в своем первоначальном описании. В описании проекта явно указано, что я не могу использовать стандартные контейнеры, функции сортировки или интеллектуальные указатели. – bradym55

+0

Или 'qsort' считается функцией сортировки? Пфф. Как вы можете сортировать, не используя функцию сортировки? Напишите свой собственный? Тогда он становится функцией сортировки. –

Смежные вопросы