0

I have text file like this:

7
a

bkjb
c


dea

hash_table is an array such that line no.-2=index of hash_table array that is every line corresponds to an element in array. The element may be empty line or character like "a\n" which will like this in text file:

a
//empty line

First number is used to decide the size an array hash_table. THe << operator is not treating empty line or '\n' char as string and hence not adding into array. I tried this but no use . Here is my try:

ifstream codes ("d:\\test3.txt"); //my text file

void create_table(int size, string hash_table[]) //creating array
{   string a;
    for(int i=0;i<size;i=i+1)
        {
        codes>>a;
        char c=codes.get();

        if(codes.peek()=='\n')
            {char b=codes.peek();
            a=a+string(1,b);
            }
        hash_table[i]=a;
        a.clear();
        }
}

void print(int size, string hash_table[])
{
    for(int i=0;i<size;i=i+1)
        {if(!hash_table[i].empty())
            {cout<<"hash_table["<<i<<"]="<<hash_table[i]<<endl;} 
        }
}

int main()
{
    int size;
    codes>>size;
    string hash_table[size];
    create_table(size, hash_table);
    print(size, hash_table);



}

NOTE: there can be any no. of empty lines with random sequence.

Community
  • 1
  • 1
Nikhil Chilwant
  • 581
  • 2
  • 10
  • 31

1 Answers1

2

Use std::getline() instead of std::ifstream::operator >>(). The >> operator will skip over whitespace, including newlines.

std::string line;
while (std::getline(codes, line)) {
    //...do something with line
}
jxh
  • 64,506
  • 7
  • 96
  • 165
  • when does this while loop terminates. It should not add EOF to array. – Nikhil Chilwant Oct 28 '13 at 16:51
  • 1
    @Nikhil It won't. This is the *correct* way to read every line from a file. If you are ever checking the `eof()` function you are almost certainly doing it wrong. This condition will stop when it tries to read past the last line. – BoBTFish Oct 28 '13 at 16:52
  • @BoBTFish I did like this [click here](http://codepad.org/HcfqMnaC) but still not working. Compiler stops working without giving any error. See the create_table() fucntion – Nikhil Chilwant Oct 28 '13 at 17:13
  • works when I delete `hash_table[i]=a;` works fine when I replace it with `cout a;` – Nikhil Chilwant Oct 28 '13 at 17:17
  • 1
    @Nikhil: your code sample makes a C-style array of strings and calls it a hash table. What the error is about is the fact that you make it a C-style array with a size that is not known at compile time. Use a std::vector and use .push_back to add new items to the vector. – Klaas van Gend Oct 29 '13 at 08:51