file

Hi every one i'am beginner in c++ and write this code for read from file ,
in file i have numbers from 1 to 10 , but when program execute , i have 2 additional zero !!!!!
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
double sales;
ifstream file("sales.dat");
if (!file.fail())
{
while (!file.eof())
{
file >> sales;
cout << sales << endl;
}
}
else
cout << "\n File failed to open.";
file.close();
return 0;
}


1
2
3
4
5
6
7
8
9
1
0
0
First, please use [ code ] [ /code ] tags (minus the spaces) when posting code.

Your problem is you're looping on eof(). The last attempt to read fails and the value stored in sales isn't overwritten, so you output it twice. Also, it appears there's some sort of whitespace between the 1 and the 0 in what should be a 10. But this is a problem in the file, not the code.

Here's how you do this:

1
2
3
4
while(file >> sales)
{
    std::cout << sales << std::endl;
}

You can do this because operator>> returns the stream itself. Used as a boolean value, a stream will evaluate to true if it's state is good(), or false otherwise. In the above snippet, you weren't checking for bad().

EDIT: also notice the call to close() is useless, because the stream's destructor will call it anyway. Just let the scope deal with it.
Last edited on
Topic archived. No new replies allowed.