What you've got is a classic case of improper loop control using eof( ).
Remember that eof( ) only tells you you've reached end of data when you've attempted to read past the end. It's like walking towards a cliff, at night, with a blindfold on. You don't know you've reached it until you take one step to far (and fall over the edge!).
Consider this smaller sample:
int num;
int total = 0;
ifstream fin ("nums.txt");
while( !fin.eof( ) )
{
fin >> num;
cout << num << " ";
total += num;
}
cout << total << endl;
If the file is dead empty, you still enter the loop because you don't know that. Input gets nothing, you output some random value, add that junk to total. Not good.
If there is data, you read numbers, adding, until the very last. Input stops at the first non-interger looking thing on the input stream, so we get the last number and halt. Display it, add it, go back to top of loop. End of file has not yet been set, so we enter the loop again. The input now attempts to read past end of file, nothing there. EOF gets set, and nothing new is stored to num (it holds the previously read value.) Display the old value, add it in again, then the loop control will halt the process.
This is essentially what's happening in your program.
First, you are working on the premise that data will always exist in 16 character chunks. If this is a guaranteed condition, how about this minor change:
myfile1.get(d); //priming read
while(!myfile1.eof())
{
for ( j=0; j<BC; j++)
for ( i=0; i < 4; i++)
{
a[i][j] = d; // plaintext
cout<<a[i][j]; // to chk how many plaintext is copied
myfile1.get(d); //reads first element of next block
}
Encrypt(a, rk);
if (myfile3.is_open())
{
for(j=0; j< BC; j ++)
for ( i=0; i<4; i++)
myfile3<<a[i][j];
}
else
cout << "Unable to open file";
}
This reads one time outside the loop - so if there is no data, you never enter the loop. The read in the inner loop is moved to the bottom, so what you end up with is attempting to read the first char of the next 16-char block. If you've just finished the last block, this then will go past the end, set EOF, and your main loop will exit correctly.
Someone is bound to say using .eof() is not a good way to control loops. In this case of character by character input, it's not soooo bad. When you get to dealing with string input, it can be troublesome. Many suggest the better approach is to either put the input statement as the condition in your loop (the input operation "returns" a non-0 or 0 value indicating successful input or failure, respectivley) or to use the .fail( ) method of the input object (which, as with .eof() requires a priming read and read at end of loop.) Either of these methods correctly handle the case of input file ending without a final newline.
There ends today's lesson. It's Saturday, I gotta go play.
Val