Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Facing problem reading file character-by-character using get()

34 views
Skip to first unread message

bintom

unread,
Sep 24, 2017, 10:20:23 AM9/24/17
to
Hi!

I have the following short program to read a text file character-by-character using get().

int main()
{ char ch;
ifstream in("Text.txt");

while(in)
{ in.get(ch);
cout.put(ch);
}

in.close();
}

In the output, I am getting the very last character in the text file appearing twice. I have no clue why ...

Thanks for any help

bintom

unread,
Sep 24, 2017, 10:23:39 AM9/24/17
to
I have the following code, which is printing the last character in the text file two times.

int main()
{ char ch;
ifstream in("Test.txt");

while(in)
{ in.get(ch);
cout.put(ch);
}

in.close();

getch();
}

Any help will be hugely appreciated.

Alf P. Steinbach

unread,
Sep 24, 2017, 11:03:58 AM9/24/17
to
Because you don't check the result of the `get` call.

Change the loop to

while( in.get( ch ) ) { cout.put( ch ); }

That's idiomatic and, because `get` returns a reference to the stream
which converts to `bool` via a call to `fail()` + negation, it's the
short version of

for( ;; )
{
char ch;
in.get( ch );
if( in.fail() )
{
break;
}
cout.put( ch );
}

But you don't want to write that.


Cheers & hth.,

- Alf

Barry Schwarz

unread,
Sep 24, 2017, 2:09:19 PM9/24/17
to
Alf has already given you the technical answer. Your confusion arises
because you made a false assumption about the state of in. Here is
one way to analyze the situation should you run into something similar
in the future. It falls under the general heading of "pretend you are
the computer".

Consider the sequence if the file contains two characters, '8' and
'9'.
You open the file. The ifstream object in now corresponds to that
file.
The while expression evaluates to true.
You read the character '8'. The operation completes normally.
You write the contents of ch ('8').
The while expression evaluates to true.
You read the character '9'. The operation completes normally.
You write the contents of ch ('9').
The while expression evaluates to true.
You attempt to read another character. There is none available.
The operation fails. Object ch is unchanged.
You write the contents of ch ('9').
Now the while expression evaluates to false and you close the file.

Reading the last character of a file and no further does not set "end
of file" status. That only happens when you attempt to read beyond
the last character.

--
Remove del for email

bintom

unread,
Sep 25, 2017, 8:03:15 AM9/25/17
to
A big thanks to both Alf and Barry.

Alf for showing the couple of lines that were missing from my code and Barry for explaining what was happening under the hood. Esp. the last paragraph stood out for its clarity.

Thanks all over again.
0 new messages