2014-11-09 2 views
1

Моя программа должна взять файл из командной строки, который должен содержать список имен (не более десяти символов), за которым следует пробел, а затем возраст, все разделенные новыми строками , Я должен создать хеш-таблицу размером 10, используя отдельную цепочку, с хэш-функцией h (x) = x mod 10, а затем распечатать таблицу по завершении.Как хэш в C++

Код:

#include <iostream> 
#include <iostream> 
#include <fstream> 
#include <sstream> 
#include <string> 
#include <ctype.h> 
#include <stdio.h> 

using namespace std; 

struct node 
{ 
    char name[10]; 
    int age; 
    node *next; 

    node() 
    { 
     memset(name, 0x0, sizeof(name)); 
     age = 0; 
    } 
}; 

int main(int argc, char *argv[]) 
{ 
    node *heads = new node[10]; 
    string currentLine; 
    char c; 
    int index = 0, fileAge, hashValue = 0; 
    node *current; 

    current = new node; 


    ifstream input(argv[1]); 

    if (input.is_open()) //while file is open 
    { 
     while (getline(input, currentLine)) //checks every line 
     { 
      istringstream iss(currentLine); 
      while (iss >> c) 
      { 
       if (iss.eof()) 
        break; 

       if (isdigit(c)) 
       { 
        iss.putback(c); 
        iss >> fileAge; 
        hashValue = fileAge % 10; 
        current->age = fileAge; 

        if ((&heads[hashValue]) == NULL) 
         heads[hashValue] = *current; 
        else 
        { 
         current->next = &heads[hashValue]; 
         heads[hashValue] = *current; 
        } 
       } 

       else 
       { 
        current->name[index] = c; 
        index++; 
       } 
      } 
     } 
    } 

    for (int x = 0; x < 10; x++) 
    { 
     printf(" Index %d: ", x); 

     current = &heads[x]; 
     if (current != NULL) 
     { 
      if (!string(current->name).empty()) 
       printf("%s (%d), ", current->name, current->age); 
     } 

     printf("\b\b\b\n"); 
    } 
} 

входного файла:

Alice 77 
John 68 
Bob 57 
Carlos 77 

Ожидаемый результат:

. 
. 
. 
Index 6: 
Index 7: Alice (77), Bob (57), Carlos (77) 
Index 8: John (68) 
. 
. 
. 

Фактический выход:

Index 7: AliceJohnBobM (77) 
Index 8: Alice John (68), 

Я не понимаю, что вызывает эту проблему, и любая помощь будет оценена по достоинству.

ответ

0

Проблема в том, что это бесконечный цикл.

current = &heads[x]; 
while (current != NULL) 
{ 
    printf("%s (%d), ", current->name, current->age); 
} 

ниже значения печатает правильно ...

current = &heads[7]; 
printf("%s (%d), ", current->name, current->age); 

Что-то, как это будет работать с несколькими линиями, но есть небольшая проблема в моем коде. Я уверен, что вы сможете это исправить. Вам нужно правильно установить «следующий» элемент и правильно переправить связанный список.

struct node 
{ 
    char name[10]; 
    int age; 
    node *next; 

    node() 
    { 
     memset(name, 0x0, sizeof(name)); 
     age = 0; 
     next = NULL; 
    } 
}; 

int main(int argc, char *argv[]) 
{ 
    node *heads = new node[10]; 

    string currentLine; 
    char c; 
    int index = 0, fileAge, hashValue = 0; 
    node *current; 

    ifstream input(argv[1]); 

    if (input.is_open()) //while file is open 
    { 
     while (getline(input, currentLine)) //checks every line 
     { 
      current = new node(); 

      istringstream iss(currentLine); 
      while (iss >> c) 
      { 
       if (iss.eof()) 
        break; 

       if (isdigit(c)) 
       { 
        current->name[index] = 0; 

        iss.putback(c); 
        iss >> fileAge; 
        hashValue = fileAge % 10; 
        current->age = fileAge; 
       } 
       else 
       { 
        current->name[index] = c; 
        index++; 
       } 
      } 

      if ((&heads[hashValue]) == NULL) 
       heads[hashValue] = *current; 
      else 
      { 
       if ((&heads[hashValue])->next == NULL) 
        heads[hashValue] = *current; 

       heads[hashValue].next = current; 

       node* next = new node; 
       heads[hashValue].next->next = next; 
       current = next; 
       index = 0; 
      } 
     } 
    } 

    for (int x = 0; x < 10; x++) 
    { 
     printf(" Index %d: ", x); 

     node *currentNode = &heads[x]; 
     while (currentNode != NULL && !string(currentNode->name).empty()) 
     { 
      printf("%s (%d), ", currentNode->name, currentNode->age); 
      currentNode = currentNode->next; 
     } 

     printf("\b\b\n"); 
    } 
} 
+0

Кроме того, вы не инициализировали имя, возраст. current = новый узел; – user1

+0

Большое спасибо. Не могли бы вы также помочь мне с проблемой наличия нескольких входов? Я буду обновлять исходное сообщение с помощью входного файла из более чем одной строки и показывать результат при компиляции с помощью этого нового кода. – iraxeje

+0

Проверьте мой последний ответ. – user1

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