Well I am attempting to read in a text file using c++. I am using vs 2010. Where should I put my text file so that my program can find it. Here is the code I am using.
#include <iostream>
#include <string>
#include <math.h>
#include <fstream>
using namespace std;
int main()
{
double index=0;
int syllabus,words,sentences;
string filename;
cout << "Enter the data file name: ";
cin >> filename;
ifstream infile;
infile.open(filename.c_str());
if(infile.fail())
{
cout << "Error opening " << filename << endl;
system("pause");
return 1;
}
?
infile.close();
system("pause");
return 0;
}
That particular code will try to open the file relative the current working directory. What the working directory is depends on how you run your program. For example, if you run your program from the explorer by, say, double clicking it, the working directory is the directory of the program executable itself. If you make a short cut to your program, you can set the working directory within the short cut. If you execute the program from an IDE, the working directory is typically where the project file is, by default.
edit for clarification: The file is relative the working directory if you specify a relative file name. If you specify an absolute file name, then the file name in the absolute name on your file system and the working directory is irrelevant.
I have another question how do I read in a text file word by word?
In your case:
std::string word;
infile >> word;
Put that in a loop to read as many words as you want.