Cannot simply read from file

I copied some code straight out of the book and cannot read from a file.
gradfile.txt is made, placed in the project directory, and has:
100
200
300
any ideas?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <fstream>
using namespace std;

int main()
{

	ifstream inputFile;
	inputFile.open("gradfile.txt");

	int number;
	while (inputFile >> number)
	{
		cout << number << endl;
	}

	
	inputFile.close();
	return 0;
}
Hi,
Try this :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
	ifstream inputFile;
	inputFile.open("gradfile.txt");
	int number;
	if(!inputFile.is_open())
	{
		cout << "Error : gradfile.txt not found" << endl;
	}
	while (inputFile >> number)
	{
		cout << number << endl;
	}
	
	inputFile.close();
	return 0;
}


And let us know if any message is found in your program output.
Last edited on
Gives me the Error: "gradfile.txt" not found
Is it not in the right spot?
Yes. Place it in the folder where your test program is.
Does that help? :)
No, its in the the "fstream" project folder...triple checked.
Hell, I put a copy in the debug folder to and tried it.
Instead of openning the executable file with your compiler, you may also try manually openning the file.
Not sure what you mean. I am referring to a book I have but I don't see anything different from what I have.
Do you mean giving the directory?
> Not sure what you mean.
Open the executable file with Windows Explorer.
Make sure your input file "gradfile.txt" is there.
Stupid me. I had "gradfile.txt.txt"...
I am doing the find the average, lowest, highest, from a file with functions and had to take it a few steps back to figure out this issue.
Thanks!
Glad it helped :)
This question is still about input from a file so i'll post here.

1
2
3
4
5
6
7
8
while (inputFile >> grades[pos])
	{
		pos++;
		inputFile >> grades[pos];
		


	}

only the high is correct.
so while the first grade is being loaded in the array
increment the counter, which is set to 0
and input the next until no more input, correct?

I used a for loop since I knew how many inputs there would be, which worked, but still don't get how the while didn't work
Last edited on
1
2
3
4
5
6
7
pos = 0;
while (inputFile >> grades[pos])
	{
		pos++;
		inputFile >> grades[pos];
		
	}


And that's it! :)
Does that help you? :)
I will try this when I get home, but this does make a bit more sense.
Topic archived. No new replies allowed.