Search code examples
c++hashtable

hashtable from input to output


I would like to implement hashtable and so far I have reading from file and something not working when I want to write first string to Tabh. Code compile without errors but nothing appears in console. Can someone help me with that? I think that I wrong implement: if (Tabp[ite].substr(0) == "a"){...}

#include <iostream>
#include <fstream>


using namespace std;

void Add(string T[], int r, long k, string w);
//void print();
//void delete();
//void stop();

int main()
{
   string linie;
   int licznik = 0;
   ifstream policz("test.txt");
   while(getline(policz, linie))
         licznik++;
   policz.close();

   string * Tabp = new string[licznik];
   fstream plik;
   plik.open("test.txt");
   string wiersz;

   for (int b =0; b<licznik; b++)
   {
         getline(plik, wiersz);
         Tabp[b] = wiersz;
   }

   string iloscprzypadkow = Tabp[0].substr(0);
   int n = stoi(iloscprzypadkow);

   string rozmiarstring = Tabp[1].substr(5,7); 
   int size = stoi(rozmiarstring);
   string * Tabh = new string[size];

   for (int ite=2; ite<licznik; ite++)
            if (Tabp[ite].substr(0) == "a")
            {
               string temp = Tabp[ite].substr(4,5);
               long klucz = stoi(temp);
               string wartosc = Tabp[ite].substr(7,14);
               Add(Tabh, size, klucz, wartosc);
            }
          //if (wyrazenie == "p")
          //{
          //}                
          //if (wyrazenie == "d")
          //}
          //{                                                             
          //if (wyrazenie == "s")
          //{                                                              
          //}

}
void Add(string Tabh[], int rozmiar, long klucz, string wartosc)
{
cout<<rozmiar<<klucz<<wartosc;
int indeks = klucz%rozmiar;
Tabh[indeks] = wartosc;
cout<<indeks<<" "<<klucz<<" "<<wartosc;
}

-------------------------
input:
1
size 10
add 13 ala
print
add 23 ola
print
delete 13
print
stop

Solution

  • The one parameter version of substr returns a substring starting at the given index thru the end of the string. So your call to Tabp[ite].substr(0) will return a copy of Tabp[ite]. To get a substring of one character, you need to specify that using two parameter version, where the second parameter is the length of substring that you want (not the end index, as it appears you're doing elsewhere in your code).

    So you'd want to use Tabp[ite].substr(0,1) == "A". Or, since it is just one character, just check that single character with Tabp[ite][0] == 'A'.