This is not correct.
Firstly, the variable n is useless. You are using a while loop, hence an incrementing variable is unnecessary. Get rid of it completely.
Secondly, you are reading from the file on line 14 and opening it on line 18. How are you reading before opening? Open the file first, THEN read. Also, two reads will be required: one before the while test (this will read the first number), and one within the while loop (this will read all subsequent numbers as long as it passes the test).
Thirdly, after opening the file, it is good programming practice to check that it is actually open. Hence, after the open statement, insert this into your code:
1 2 3 4 5
|
if(!myfile.is_open())
{
cout << "FILE NOT OPENED!";
return 0;
}
|
Its a simple statement that will output "FILE NOT OPENED" to the screen and end the program if your file did not open successfully. If it did open successfully, the entire if-statement will be ignored and it will carry on with the program.
Fourthly, cout temp within the while loop. Thats the easiest way to print out your file onto the screen
Fifthly, the test
while(!fin.eof())
will actually NOT cout your entire file. It will cout everything except for the last piece of information in the file. Say your file consisted of a list of numbers 1-10. Your code using this while test would only print the numbers 1-9. Why is this? Simply trace the program and you'll understand.
If you want to cout your entire file, simply insert the name of your file (just the file name and nothing else) in your while test. So it would be
while(fin)
.
Sixthly, props on remembering to close the file at the end. I always forget to do that :)