Reading Files

I can't seem to get my program to read a file that's saved on my computer. Here's my code:

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()

{
ifstream inputfile;
string name;

inputFile.open("Friends.txt");
cout << "Reading data from a file.\n";

inputFile >> name;
cout << name << endl;

inputFile >> name;
cout << name << endl;

inputFile >> name;
cout << name << endl;

inputFile.close();

return 0;
}

If anyone could help me out, and tell me what I'm doing wrong, that'd be great.
"Friends.txt" has to be in the same location as the files for your code. Also make sure you spelled it correctly. Capitalization matters.
What exactly do you mean by "the same location as the files for my code"?
He means for them to be in the working directory for the executable of your code. For example, if you ran the executable from one folder, it needs to be in the same folder as the executable is.

Also, you should check if the file is opened before reading:
1
2
3
4
5
6
7
8
9
10
#include <fstream>
// ...

int main() {
    std::ifstream inputFile ("File.txt");
    if (!inputFile.is_open()) {
        // print an error
        return 1; // file wasn't opened
    }
}
Aright I think I got it. Thanks!
i hope your code isn't big error it only miss spelling because C++ is case sensitive, you created an object from ifstream as object name inputfile
and it is not same as you declared inputfile and the way you used because the character ' f ' is a small when you declared as object name and it is capital when you used.
and also the way you open the file is right
the file is open default in your program location so you have to check if the file is exist in your project folder
and i hope it will be OK if you do this way
thank you
Yes. I changed that letter to a capital "F" and also put the txt file in the right folder and now the program is working. Thanks again!
Topic archived. No new replies allowed.