Форум программистов
 

Восстановите пароль или Зарегистрируйтесь на форуме, о проблемах и с заказом рекламы пишите сюда - alarforum@yandex.ru, проверяйте папку спам!

Вернуться   Форум программистов > C/C++ программирование > Общие вопросы C/C++
Регистрация

Восстановить пароль
Повторная активизация e-mail

Купить рекламу на форуме - 42 тыс руб за месяц

Ответ
 
Опции темы Поиск в этой теме
Старый 08.01.2015, 18:34   #1
Copter1024
 
Регистрация: 08.01.2015
Сообщений: 3
По умолчанию Структура

Здравствуйте! Есть программка, работающая со структурой: название товара (item), стоимость, розничная цена (cost) и другие поля (см. ниже). Проблема в функции remove_item(): когда вводишь название товара для удаления из массива структур, программа вылетает без предупреждения. Ошибка явно в этой функции. Подскажите, что не так.
Код:
#include <iostream>
#include <cctype>
#include <cstring>
#include <cstdlib>
using namespace std;

const int SIZE = 4;


struct inv_type {
  char item[40]; // name of item
  double cost;   // cost
  double retail; // retail price
  int on_hand;   // amount on hand
  int lead_time; // number of days before resupply
}  invtry[SIZE];

void enter(), init_list(), display();
void update(), input(int i);
void remove_item();
int menu();

int main()
{
  char choice;

  init_list();

  for(;;) {
    choice = menu();
    switch(choice) {
      case 'r': remove_item();
        break;
      case 'e': enter();
        break;
      case 'd': display();
        break;
      case 'u': update();
        break;
      case 'q': return 0;
    }
  }
}

// Initialize the inv_type_info array.
void init_list()
{
  int t;

  // a zero length name signifies empty
  for(t=0; t<SIZE; t++) *invtry[t].item = '\0';
}

// Get a menu selection.
int menu()
{
  char ch;

  cout << '\n';
  do {
    cout << "(R)emove Item\n";
    cout << "(E)nter\n";
    cout << "(D)isplay\n";
    cout << "(U)pdate\n";
    cout << "(Q)uit\n\n";
    cout << "choose one: ";
    cin >> ch;
  } while(!strchr("reduq", tolower(ch)));
  return tolower(ch);
}

// Enter items into the list.
void enter()
{
  int i;

  // find the first free structure
  for(i=0; i<SIZE; i++)
    if(!*invtry[i].item) break;

  // i will equal SIZE if the list is full
  if(i==SIZE) {
    cout << "List full.\n";
    return;
  }

  input(i);
}

// Input the information.
void input(int i)
{
  // enter the information
  cout << "Item: ";
  cin >> invtry[i].item;

  cout << "Cost: ";
  cin >> invtry[i].cost;

  cout << "Retail price: ";
  cin >> invtry[i].retail;

  cout << "On hand: ";
  cin >> invtry[i].on_hand;

  cout << "Lead time to resupply (in days): ";
  cin >> invtry[i].lead_time;
}

// Modify an existing item.
void update()
{
  int i;
  char name[80];

  cout << "Enter item: ";
  cin >> name;

  for(i=0; i<SIZE; i++)
    if(!strcmp(name, invtry[i].item)) break;

  if(i==SIZE) {
    cout << "Item not found.\n";
    return;
  }

  cout << "Enter new information.\n";
  input(i);
}

// Display the list.
void display()
{
  int t;

  for(t=0; t<SIZE; t++) {
    if(*invtry[t].item) {
      cout << invtry[t].item << '\n';
      cout << "Cost: $" << invtry[t].cost;
      cout << "\nRetail: $";
      cout << invtry[t].retail << '\n';
      cout << "On hand: " << invtry[t].on_hand;
      cout << "\nResupply time: ";
      cout << invtry[t].lead_time << " days\n\n";
    }
  }
}

// Remove an existing item
void remove_item()
{
  int i;
  char name[40];

  cout << "Enter item to remove: ";
  cin >> name;

  for(i=0; i<SIZE; i++)
    if(!strcmp(name, invtry[i].item)) break;

  if(i==SIZE) {
    cout << "Item not found.\n";
    return;
  }

  strcpy(invtry[i].item, '\0');
  //invtry[i].item = '\0';
  invtry[i].cost = 0.0;
  invtry[i].retail = 0.0;
  invtry[i].on_hand = 0;
  invtry[i].lead_time = 0;
}
Copter1024 вне форума Ответить с цитированием
Старый 08.01.2015, 18:38   #2
Copter1024
 
Регистрация: 08.01.2015
Сообщений: 3
По умолчанию

Т.е. удаление записи (структуры) из массива структур заключается в записи нулевого символа в поле item и обнулении double- и int-полей. Но почему-то оно заставляет программу вылетать с ошибкой.

Кстати, при компиляции выдается warning
Код:
||=== Build: Debug in 005 (compiler: GNU GCC Compiler) ===|
C:\Projects\005\main.cpp||In function 'void remove_item()':|
C:\Projects\005\main.cpp|166|warning: null argument where non-null required (argument 2) [-Wnonnull]|
||=== Build finished: 0 error(s), 1 warning(s) (0 minute(s), 2 second(s)) ===|
Это сообщение компилятор относит к строке
Код:
strcpy(invtry[i].item, '\0');
Copter1024 вне форума Ответить с цитированием
Старый 08.01.2015, 18:45   #3
Stilet
Белик Виталий :)
Старожил
 
Аватар для Stilet
 
Регистрация: 23.07.2007
Сообщений: 57,097
По умолчанию

Цитата:
strcpy(invtry[i].item, '\0')
Замени на
Код:
memset(&invtry[i].item,sizeof(invtry[i].item),0) ;
I'm learning to live...
Stilet вне форума Ответить с цитированием
Старый 08.01.2015, 19:15   #4
Copter1024
 
Регистрация: 08.01.2015
Сообщений: 3
По умолчанию

Stilet
Извини, ты не мог бы прокомментировать этот код, чтобы было более понятно?

Может, ты это имел в виду?
Код:
memset(&invtry[i].item, 0, sizeof(invtry[i].item)) // Заполняем нулевыми символами всё поле item;

Последний раз редактировалось Stilet; 08.01.2015 в 21:02.
Copter1024 вне форума Ответить с цитированием
Старый 08.01.2015, 21:01   #5
Stilet
Белик Виталий :)
Старожил
 
Аватар для Stilet
 
Регистрация: 23.07.2007
Сообщений: 57,097
По умолчанию

Чьёрт побьери... Я параметры местами попутал?
Это все гайморит, голова последнюю неделю из-за перепадов погоды совсем не варит...
Хорошо что ты обратил на это внимание, какое-нить школоло бы даже не почесалось проверить...
I'm learning to live...
Stilet вне форума Ответить с цитированием
Ответ


Купить рекламу на форуме - 42 тыс руб за месяц



Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
Структура if zumm PHP 9 13.05.2012 17:29
Структура Сеня2 Visual C++ 1 09.05.2012 23:26
Структура Valentina2011 Общие вопросы C/C++ 0 06.05.2012 22:40
Структура на С++ Darh Помощь студентам 3 16.12.2009 23:27
Структура Superlotles Помощь студентам 5 14.09.2009 23:29