Help reading files

My code is below. The file I am trying to open is Random.txt located in "C:\Users\Tony\Downloads". I have tried inputting "Random.txt" "C:\\Users\\Tony\\Downloads\\Random.txt" "C:\Users\Tony\Downloads\Random.txt" and none of these are working, I keep getting my error message. Is there something wrong with the code or am I inputting the file name incorrectly?

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()

{
//Declaring variables
ifstream inputFile;
string fileName;
int number, sum;
double average;


//Getting file name from user
cout << "Please enter the name of the file that you wish to open.\n";
cin >> fileName;

//Opens file
inputFile.open(fileName.c_str());

//Verifies file was opened
if (inputFile)
{

//Reads numbers from file
while (inputFile >> number)
cout << "The number of numbers in the file is: " << inputFile;

//Close file
inputFile.close();
}
else
{

//Display error
cout << "Error opening the file.\n";
}
return 0;
}
Last edited on
"C:\\Users\\Tony\\Downloads\\Random.txt" or "C:/Users/Tony/Downloads/Random.txt" should work. Not sure if it makes a difference but try closing all programs that have the file opened.
"C:\\Users\\Tony\\Downloads\\Random.txt" should work. Two backslashes is better, because one backslash could be a comment like newline or other things.
I have tried these, and they are not working. I still keep getting the Error opening the file message.
Print the filename and see that it outputs correctly. Note that when you type in the filename you should leave out the double quotes.
http://www.docdroid.net/wepp/location-picture.docx.html
The link is a link to an uploaded document with pictures of the properties box. The second picture is after I attempted to move the file to desktop.
Could you try putting your file where your project is, where all the classes go etc, and then just use Random.txt to open it.
Looking at your pictures... the computer that is compiling the program is not your computer. Therefore your input file does not exist on the computer that is doing the compiling.
Ok, is there a way for the compiler to access my local computer?
I would upload it to the server, but I think my teacher wants users the program to access the computer.
If you're moving from computer to computer, put the file in your project.
Ok, thanks for the help
https://www.youtube.com/watch?v=HcONWqVyvlg&index=64&list=PLAE85DE8440AA6B83&ab_channel=thenewboston

Watch this video to know where to put the file and how to open it once its in your project.
On second thoughts... you should probably not use double backslashes (\\) when passing the arguments from the console window, but I'm not sure. You can also forward slashes instead (/).
Topic archived. No new replies allowed.