473,385 Members | 1,753 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

FILESTREAM HELP NEEDED

#include<fstream>
using namespace std;

int main()
{
ifstream in;
ofstream out;
int a=0;
in.open("a.txt");
out.open("b.txt");
while(!in.eof())
{
in>>a;
out<<a<<endl;
}
return 0;
}

a.txt contains:

1
2
3
4
5
6
7
8

b.txt contains at the end of the program:

1
2
3
4
5
6
7
8
8

Instead of:

1
2
3
4
5
6
7
8

How can i prevent 8 from printing twice?

Nov 22 '05 #1
18 1325

"coinjo" <co****@gmail.com> wrote in message
news:11**********************@g49g2000cwa.googlegr oups.com...
#include<fstream>
using namespace std;

int main()
{
ifstream in;
ofstream out;
int a=0;
in.open("a.txt");
out.open("b.txt");
while(!in.eof())
{
in>>a;
out<<a<<endl;
}
return 0;
}


First, you should be following the advice "mlimber" gave to your previous
post:

Pass the filenames to the constructors of the stream objects, instead of
calling open explicitly.

Then, pust the input statement in your while condition, not eof(). Using
eof() in your while statement is incorrect, since it does not detect the end
of file until _after_ it fails to read. The eof() test should be used
_after_ a read fails, to detect if the _reason_ for the read failure was an
end-of-file (as opposed to some other unexpected condition).

This is undoubtedly the cause of your problem. If there's a blank line at
the end of your text file (which there often is, because whoever enters the
data usually hits Enter after each line), then the last time through the
loop, it tries to read a blank line into an integer, which fails. Since the
read failed, the variable a still contains what it did before, which is the
value 8. So, you output 8.

-Howard

Nov 22 '05 #2

coinjo wrote:
#include<fstream>
using namespace std;

int main()
{
ifstream in;
ofstream out;
int a=0;
in.open("a.txt");
out.open("b.txt");
while(!in.eof())
{
in>>a;
out<<a<<endl;
}
The eof() method tells you if the *last* input operation attempted to
read past the EOF, not if the *next* input operation will read past the
EOF, so your loop executes one too many times. Here's how the last
three iterations go:

1. Test for EOF
2. Not at EOF, so read next character
3. Next character read was 8, assign to a
4. Write contents of a to out
5. Test for EOF
6. Not at EOF, so read the next character
7. Next character read was EOF, so read fails; a is left unchanged
8. Write contents of a to out
9. Test for EOF
10. At EOF, exit loop

Instead of testing on in.eof(), test on the result of the input
operator:

while (in >> a)
{
out << a << endl;
}
if (in.eof())
{
cerr << "hit end of file" << endl;
}
else
{
cerr << "some other error" << endl;
}
return 0;
}


Nov 22 '05 #3

"Howard" <al*****@hotmail.com> wrote in message
news:OA*******************@bgtnsc05-news.ops.worldnet.att.net...
This is undoubtedly the cause of your problem. If there's a blank line at
the end of your text file (which there often is, because whoever enters
the data usually hits Enter after each line), then the last time through
the loop, it tries to read a blank line into an integer, which fails.
Since the read failed, the variable a still contains what it did before,
which is the value 8. So, you output 8.


Come to think of it, it will behave this way even if there's _not_ an extra
line at the end, because the last successful read (of the value 8 into a)
will still not have set the eof flag. That flag only gets set after a
failure to read occurs.

-Howard
Nov 22 '05 #4
In message <11**********************@g49g2000cwa.googlegroups .com>,
coinjo <co****@gmail.com> writes
[...]
while(!in.eof())

How can i prevent 8 from printing twice?

By reading TFFAQ:

http://www.parashift.com/c++-faq-lit....html#faq-15.5

--
Richard Herring
Nov 22 '05 #5
coinjo wrote:
#include<fstream>
using namespace std;

int main()
{
ifstream in;
ofstream out;
int a=0;
in.open("a.txt");
out.open("b.txt");
while(!in.eof())
{
in>>a;
out<<a<<endl;
}
return 0;
}


It's one of the mysteries of the universe, why does every single newbie
make the mistake that coinjo made? Coinjo I'd really appreciate it if
you told me why you wrote 'while (!in.eof())' in your code. Did you read
it in a book? Did it just seem right? If I can understand why you wrote
the code like that, I'll be better able to help the next newbie here who
has made the same mistake.

Thanks,
John
Nov 22 '05 #6
John Harrison <jo*************@hotmail.com> wrote:
coinjo wrote:
#include<fstream>
using namespace std;

int main()
{
ifstream in;
ofstream out;
int a=0;
in.open("a.txt");
out.open("b.txt");
while(!in.eof())
{
in>>a;
out<<a<<endl;
}
return 0;
}


It's one of the mysteries of the universe, why does every single newbie
make the mistake that coinjo made? Coinjo I'd really appreciate it if
you told me why you wrote 'while (!in.eof())' in your code. Did you read
it in a book? Did it just seem right? If I can understand why you wrote
the code like that, I'll be better able to help the next newbie here who
has made the same mistake.


I am not coinjo, but I have a guess. Maybe people are trying to emulate
the C idiom of:

int c;
FILE* fp = fopen("file", "r");
while ((c = getc(fp) != EOF) {
/* ... */
}

If this came out of a book, my guess is that some book authors who write
C++ books really don't know C++, but C, and just do things the C way
with minor changes to try and make it look like C++.

--
Marcus Kwok
Nov 22 '05 #7
John Harrison <jo*************@hotmail.com> wrote:
coinjo wrote:
#include<fstream>
using namespace std;

int main()
{
ifstream in;
ofstream out;
int a=0;
in.open("a.txt");
out.open("b.txt");
while(!in.eof())
{
in>>a;
out<<a<<endl;
}
return 0;
}


It's one of the mysteries of the universe, why does every single newbie
make the mistake that coinjo made? Coinjo I'd really appreciate it if
you told me why you wrote 'while (!in.eof())' in your code. Did you read
it in a book? Did it just seem right? If I can understand why you wrote
the code like that, I'll be better able to help the next newbie here who
has made the same mistake.


I am not coinjo, but I have a guess. Maybe people are trying to emulate
the C idiom of:

int c;
FILE* fp = fopen("file", "r");
while ((c = getc(fp)) != EOF) {
/* ... */
}

If this came out of a book, my guess is that some book authors who write
C++ books really don't know C++, but C, and just do things the C way
with minor changes to try and make it look like C++.

--
Marcus Kwok
Nov 22 '05 #8

"Marcus Kwok" <ri******@gehennom.net> wrote in message
news:dl**********@news-int.gatech.edu...
John Harrison <jo*************@hotmail.com> wrote:
coinjo wrote:
#include<fstream>
using namespace std;

int main()
{
ifstream in;
ofstream out;
int a=0;
in.open("a.txt");
out.open("b.txt");
while(!in.eof())
{
in>>a;
out<<a<<endl;
}
return 0;
}
It's one of the mysteries of the universe, why does every single newbie
make the mistake that coinjo made? Coinjo I'd really appreciate it if
you told me why you wrote 'while (!in.eof())' in your code. Did you read
it in a book? Did it just seem right? If I can understand why you wrote
the code like that, I'll be better able to help the next newbie here who
has made the same mistake.


I am not coinjo, but I have a guess. Maybe people are trying to emulate
the C idiom of:

int c;
FILE* fp = fopen("file", "r");
while ((c = getc(fp)) != EOF) {
/* ... */
}


This isn't really different from the way it's done with
C++ streams. The above snippet also checks for EOF after
reading, not before.

If this came out of a book, my guess is that some book authors who write
C++ books really don't know C++, but C, and just do things the C way
with minor changes to try and make it look like C++.


IMO with respect to this issue, the 'C way' and 'C++ way' are
the same (check EOF after reading, not before).

-Mike
Nov 22 '05 #9
Mike Wahler wrote:

"Marcus Kwok" <ri******@gehennom.net> wrote in message
news:dl**********@news-int.gatech.edu... >John Harrison
<jo*************@hotmail.com> wrote:
coinjo wrote: while(!in.eof())
{
in>>a;
out<<a<<endl;
}
return 0;
> }
I am not coinjo, but I have a guess. Maybe people are trying to
emulate the C idiom of:

int c;
FILE* fp = fopen("file", "r");
while ((c = getc(fp)) != EOF) {
/* ... */
}


This isn't really different from the way it's done with
C++ streams. The above snippet also checks for EOF after
reading, not before.


Right, the C++ example shown above actually is closer to:

while(!feof(fp))
{
}

Which gives the same sort of error.

Brian

Nov 22 '05 #10
John Harrison wrote:
It's one of the mysteries of the universe, why does every single newbie
make the mistake that coinjo made? Coinjo I'd really appreciate it if
you told me why you wrote 'while (!in.eof())' in your code. Did you read
it in a book? Did it just seem right? If I can understand why you wrote
the code like that, I'll be better able to help the next newbie here who
has made the same mistake.


My guess is that it's two reasons:

1. The textual description is "While we're not at the end of file, do
something". This is an accurate description, but does not map cleanly
onto the C FILE* idiom or the C++ istream idiom.

2. It's a Pascal-ism. Instructors today probably learned on Pascal,
which did use that idiom:

while not eof(file) do
(* read your data and process *)
end;
Nov 22 '05 #11
It just seems right to me. Please help me!

Nov 22 '05 #12

coinjo wrote:
It just seems right to me. Please help me!


Lot's of people have given an explanation and the answer, including a
link to the FAQ

http://www.parashift.com/c++-faq-lit....html#faq-15.5

Have you tried what's been suggested? If so and it's still not working,
post the new code so people can look at it.

Or do you not understand what's been suggested? If that's the case,
explain what it is that you're not clear on and someone can try and
give you another explanation.

Gavin Deane

Nov 22 '05 #13
In message <11**********************@f14g2000cwb.googlegroups .com>,
coinjo <co****@gmail.com> writes
It just seems right to me. Please help me!

Already did.

Your problem is that eof() doesn't mean what you think it means.
You want it to mean "you have reached at the end of the file", but it
actually says "you have tried to read _beyond_ the end of the file". So
you need to test the file state after reading, not before.

--
Richard Herring
Nov 22 '05 #14
"coinjo" <co****@gmail.com> wrote in message
news:11**********************@f14g2000cwb.googlegr oups.com...
It just seems right to me. Please help me!


It's already been explained to you with a way to fix it. Another quick fix
is:

int main()
{
ifstream in("a.txt");
ofstream out("b.txt");
while(!in.eof())
{
in>>a;
if ( !in.eof() )
out<<a<<endl;
}
return 0;
}

Does that make more sense what the problem is? eof() is not set to true
until AFTER the input is read. but you are reading the input, and writing
it. But the input could of failed because end of file was reached. So
either change the logic as suggested before, or put in another test for
eof() there.

How it actually SHOULD be:

int main()
{
ifstream in("a.txt");
ofstream out("b.txt");
while( in>>a )
{
out<<a<<endl;
}
return 0;
}

in >> a returns false (I believe) when eof() is reached or some other error
has occured.
Nov 22 '05 #15
>> "Marcus Kwok" <ri******@gehennom.net> wrote in message
> I am not coinjo, but I have a guess. Maybe people are trying to
> emulate the C idiom of:
>
> int c;
> FILE* fp = fopen("file", "r");
> while ((c = getc(fp)) != EOF) {
> /* ... */
> }
Mike Wahler wrote:
This isn't really different from the way it's done with
C++ streams. The above snippet also checks for EOF after
reading, not before.

Default User <de***********@yahoo.com> wrote: Right, the C++ example shown above actually is closer to:

while(!feof(fp))
{
}

Which gives the same sort of error.


Sorry, yes, this is what I meant.

--
Marcus Kwok
Nov 22 '05 #16

"red floyd" <no*****@here.dude> wrote in message
news:dJ*****************@newssvr13.news.prodigy.co m...
John Harrison wrote:
It's one of the mysteries of the universe, why does every single newbie
make the mistake that coinjo made? Coinjo I'd really appreciate it if you
told me why you wrote 'while (!in.eof())' in your code. Did you read it
in a book? Did it just seem right? If I can understand why you wrote the
code like that, I'll be better able to help the next newbie here who has
made the same mistake.


My guess is that it's two reasons:

1. The textual description is "While we're not at the end of file, do
something". This is an accurate description, but does not map cleanly
onto the C FILE* idiom or the C++ istream idiom.

2. It's a Pascal-ism. Instructors today probably learned on Pascal,
which did use that idiom:

while not eof(file) do
(* read your data and process *)
end;


Correct, at least in my experience. My college courses mostly used Pascal
to teach programming, and both the algorithms and the code examples used
were phrased in that "while not eof" form. I also used that form when I
first returned to C++ (from Delphi), and was quickly corrected - in this
very forum. Since we don't have a way to stop posters and give them this
info before they ask, the best thing is to just take it in stride, point out
their mistake (gently), and guide them to the FAQs.

-Howard
-Howard

Nov 22 '05 #17

"Jim Langston" <ta*******@rocketmail.com> wrote in message
news:74******************@fe03.lga...
"coinjo" <co****@gmail.com> wrote in message
news:11**********************@f14g2000cwb.googlegr oups.com...
It just seems right to me. Please help me!
It's already been explained to you with a way to fix it. Another quick
fix is:

int main()
{
ifstream in("a.txt");
ofstream out("b.txt");
while(!in.eof())
{
in>>a;
if ( !in.eof() )
out<<a<<endl;
}
return 0;
}

Does that make more sense what the problem is? eof() is not set to true
until AFTER the input is read. but you are reading the input, and writing
it. But the input could of failed because end of file was reached. So
either change the logic as suggested before, or put in another test for
eof() there.

How it actually SHOULD be:

int main()
{
ifstream in("a.txt");
ofstream out("b.txt");
while( in>>a )
{
out<<a<<endl;
}
return 0;
}

in >> a returns false (I believe)


Yes.
when eof() is reached or some other error has occured.


Yes. Which is why it's common at the end of such loops
to distinguish between eof and error:

while(in >> a)
{
}
if(!in.eof())
; // trouble
else
; // eof

-Mike
Nov 22 '05 #18
It is ok now thanks.

Nov 22 '05 #19

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
by: Toby Mathews | last post by:
Hi, In an ASP.Net application I want to convert open create a FileStream object from a System.Drawing.Image - is this possible? I create an instance of an Image object using the FromFile method,...
9
by: Tom | last post by:
I am working with the this object as oppose to the StreamReader object becuase I need to access a file (to find the contents) while an external application is updating the file. When I was...
5
by: Nadav | last post by:
Hi, I am using FileStream's Async API: BeginRead/EndRead, upon completion callback execution I use the read data and call EndRead, Taking that in mind, I Wonder... does calling EndRead will cause...
5
by: Chris Fink | last post by:
How do I load a string into a FileStream without going to disk? For example, string abc = "This is a string"; How do I load abc into a FileStream? FileStream input = new FileStream(.....);
7
by: Nathan Sokalski | last post by:
I am having a problem saving an image with the same name it originally had. I have two similar versions of my code, one in which I close the FileStream used to open the original image before saving,...
4
by: Lloyd Dupont | last post by:
I need to access big data in a readonly fashion. I was thinking to open a FileStream and seek and read as needed. I was wondering if it was worth doing my own FileStream class which would use...
3
by: Arpan | last post by:
A file can be read using only the StreamReader object like this: Dim sReader As StreamReader sReader = New StreamReader(Server.MapPath("File1.txt")) While(sReader.Peek -1)...
2
by: ewingate | last post by:
The following code which is supposed to dynamically create files with incrementing names is throwing an exception due to the inclusion of the DateTime.Now component of the sReportSave string: ...
4
by: DR | last post by:
When using System.IO.FileStream, I write 8 bytes, then seek to the start of the file, does the 8 bytes get flushed on seek and the buffer become a readbuffer at that point instead of being a write...
3
by: paradigmshift | last post by:
I am looking at how to move data from a file to a memory stream. This data will be needed many times over and over so i don't want to have to rely on the system to keep the information cashed for...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.