I want to see if my program works but the file that I want to open wont open!!!
The numbers that the program should get are as follows:
47
89
65
36
12
25
17
8
62
10
87
62
also my do loop to check if it works keeps on telling me that I didn't open it right!
the file name is numbers.txt I TYPE that but it keeps giving me the error!
I don't know if the rest of the program is right because the file won't open properly and I keep getting garbage!
What I need to do is this:
Write a program that asks the user for a file name. Assume the file contains a series of numbers, each written on a separate line. The program should read the contents of the file into an array and then display the following date: THE LOWEST NUMBER, HIGHEST #, TOTAL OF #'S AND THE AVERAGE.
Your do-while loop will run one time regardless of whether the file opened correctly or not. That is the nature of the do-while loop; it will run once regardless of the test condition. Only after it has run once will it check the condition.
// ifstream infile;
cout << "Hello, please enter the file you want to use: \n";
cin >> filename;
//infile.open(filename.c_str());
//infile.clear(); // This is not needed here. It is only needed if the opening fails. Also start using the constructor as the primary way of opening the file:
ifstream infile(filename.c_str()); // The c_str() is not needed if you use a C++11 compiler.
do
{
cout << "An Error has occured, please enter file"
<< " name again please\n";
cin >> filename;
infile.clear();
infile.open(filename.c_str());
} while (infile.fail());
Normally if a file doesn't open the first time the user won't know what to do, so it may be better to just abort the program at this point.
But if you want to try again then you must try to open the file again, not just ask for the file name.
If the file doesn't open it usually means that the file is not in the proper directory. If you just specify the file name with out path information the file must be in the current working directory. This can be in different places depending on how you are running the program. If you are running the program from your IDE, the IDE controls where the current working directory is located. Many times it is in the same directory where the project files are located or in the directory where the executable is located. Check your compiler documentation to determine the correct location.
Another quick way of determining where the current directory is located is to open a file, that doesn't exist using a unique, easily searchable file name, for output. The output file will create a file if one doesn't exist by default, unlike an input stream where the file must exist using the default open modes.