Having trouble reading from a file

I am writing a program for a class. I am supposed to write a text file holding some numbers in it. The text file I have has 5, 10, 15, 20, and 25 all on separate lines. It looks to me and to everything I am checking that I am writing the code correctly to read the numbers from the file. Help is greatly appreciated as I am completely lost. When I run the program, I only get the error message that I have wrote.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main()
{
	// Declare variables
	ifstream inputFile;
	int number;

	// Open the file
	inputFile.open("Numbers.txt");
	cout << "The numbers in the file are:\n";

	// Display error when file does not open
	if (!inputFile)
		cout << "Error opening the file, the program will end with no file.\n";

	// Provide alternative for when file does open
	else
	{
		// Read the numbers in the file
		while (inputFile >> number)
		{
			// Display the numbers in the file
			cout << number << endl;
			numofnumbers++;
		}
	}

	// Close the file
	inputFile.close();

	return 0;
}
Last edited on
Hello Tipper199,

Two things will cause this error message to display:

1. The file name is spelled incorrectly. This is not the case.

2. The file is in the wrong directory. It need to be in the directory where your file for "main" is located.

When I put the input file in the correct directory the program worked.

Hope that helps,

Andy
Won’t be able to get back to my computer until tomorrow, I’ll update on if it solved my problem. Thanks for the help
So I have the file saved in the same director where my main is located. I am still not getting the correct results. Very frustrating and I don't know what to do now!
The file needs to be in the same directory as the executable, or more specifically, in your program's working directory.
Last edited on
Hello Tipper199,

Sorry for the delay. My laptop has been acting up and I have not had the opportunity to sue it as much a I would like.

Accepting that the file is in the correct directory the the most likely cause is that there is something different between the name used in the program and the name that is stored on the drive. I once had a case where I entered the file name as "Data.txt", but when it was saved the file name was "Data.txt.txt". It did take awhile to notice the difference.

Try copying the name where the file is stored, Windows "File Explorer" or what ever you use, and paste it above the name in the program to see if there is any difference in spelling.

Sometimes pasting over what is there can help. If that does not work try deleting the name and retyping it.

Hope that helps,

Andy
Topic archived. No new replies allowed.