C++ I/O streams help

Dumzaz

Active Member
Joined
Jul 23, 2007
Messages
38
Reaction score
0
Please help here. I cannot figure out whats wrong with this code. I need this to read each number from the file numbers.dat, store it in variable next, and sum the numbers while there are numbers to read. It keeps giving me 0 as the output.

#include <fstream>
#include <iostream>

int main( )
{
using namespace std;
ifstream ins;
ins.open("numbers.dat");
int next;
int sum = 0;

ins >> next;
while (ins >> next)
{

sum = sum + next;
ins >> next;
}
ins.close();
cout << sum << endl;
return 0;
}

Numbers.dat

1
2
3
4
5

Am obviously missing something ... pls help !!!!!!!!!!!!:confused:
 
For starters, if you named the file "Numbers.dat", opening "numbers.dat" will fail (numbers.dat doesn't exist => remember, it's case-sensitive).

You should always use error-checking! This is very important!

This code should do what you want (given that "Numbers.dat" exists).

Code:
#include <fstream>
#include <iostream>
using namespace std;

int main()
{
	int next;
	int sum = 0;

	ifstream ins;
	ins.open("Numbers.dat");
	if (!ins)
	{
		cerr << "Unable to open file" << endl;
		exit(1);   // call system to stop
	}

	while (ins >> next)
	{
		cout << next << endl;
		sum = sum + next;
	}

	cout << "Sum: " << sum << endl;

	ins.close();
	return 0;
}
 
but of course, thanks. I was working off 2 different folders and everytime i was checking the wrong one and i could see the file 'numbers.dat' - only it was not in the same folder as my running program. If only I had used that error checking . thanks.

:)
 
no, windows. Would it make a difference? Been considering Linux but am still deciding which distro to use. Got Impi in one of my Cd's from 2006. Have not seen much of that in use lately though.
 
no, windows. Would it make a difference? Been considering Linux but am still deciding which distro to use. Got Impi in one of my Cd's from 2006. Have not seen much of that in use lately though.

Would mainly make a difference in that Linux is case-sensitive for file-names, whereas Windows (in general) is not
 
No I didn't read you post properly, saw now that you had the file in a different folder. Case doesn't matter in Windows for file/directory names.

EDIT: sn3rd beat me to it :p

My personal opinion is to stick to Windows, Visual C++ is the best in my opinion, in terms of debugging but it does have it's share of problems. I used K-Develop in Linux didn't really like it much but perhaps that isn't the best IDE, didn't really have time to test other options.
 
Top
Sign up to the MyBroadband newsletter
X