When I use the code recommended in the book, I get an error. I am using NetBeans 6.8 for Mac.
Here is the code:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream in开发者_运维百科putFile;
int number;
inputFile.open("MacintoshHD/Users/moshekwiat/Desktop/random.txt");
inFile >> number;
cout<<endl <<number<<endl;
inputFile.close();
return (0);
}
Here is the error:
main.cpp:20: error: 'inFile' was not declared in this scope
What needs to be done?? Thank You
Replace inFile with inputFile.
Problem 1 (the one the compiler sees) is a simple typo: inFile should be inputFile. Do make sure you check for typos like this before posting to Stack Overflow.
Problem 2: the path name to your file is probably wrong, and generally, when you try to read from a stream that couldn't be initialized properly because the file couldn't be opened, you'll get 0.
In this case the path you specified is a relative path to the file from the directory your program was launched in, so whatever directory you ran the program from would need a subdirectory called "MacintoshHD", then "Users", then... you get the idea. To get the correct path, right-click on the file in the Finder and select "Get Info". Under "Where: " you'll see the correct path to the directory that contains your file; it will probably say "/Users/moshekwiat/Desktop". Add "/random.txt" to that and that should be the path you use.
Normally, C++ programmers will write code to make sure the file opens correctly before reading from it. A simple way to check for that after initializing inputFile, but before trying to read from it is:
if (! inputFile) {
cerr << "Could not open the file!" << endl;
return 1; // returning non-0 status is customary
// if your program encounters an error
}
Change inFile
to inputFile
For a start, there's no 'inFile' object in your code.
inFile >> number;
Look again:
ifstream inputFile;
change inFile to inputFile
Use inputFile instead of inFile
精彩评论