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.
#include <iostream>
#include <fstream>
#include <string>
usingnamespace 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;
}
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!
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.