Reputation: 649
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.
Upvotes: 0
Views: 4845
Reputation: 70502
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
}
Upvotes: 2