Моя программа должна взять файл из командной строки, который должен содержать список имен (не более десяти символов), за которым следует пробел, а затем возраст, все разделенные новыми строками , Я должен создать хеш-таблицу размером 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),
Я не понимаю, что вызывает эту проблему, и любая помощь будет оценена по достоинству.
Кроме того, вы не инициализировали имя, возраст. current = новый узел; – user1
Большое спасибо. Не могли бы вы также помочь мне с проблемой наличия нескольких входов? Я буду обновлять исходное сообщение с помощью входного файла из более чем одной строки и показывать результат при компиляции с помощью этого нового кода. – iraxeje
Проверьте мой последний ответ. – user1