views:

242

answers:

3

I know this is a noob question, but I've worked with Python before and when you wanted to simply access a .txt file for example, all you had to do was make sure the txt file was in the same directory. I have the following C++ code below but it's not finding the Numbers.txt file that I have saved on my desktop. All I have in the file is one line of numbers of type double. All I want to do is to find the average of all of the numbers in the file. The program runs fine, but it doesn't print the output correctly. After checking to see what is printing into output by just printing output[0], I've discovered that the file is not copying it's contents into the array. Could someone clear this little problem up for me or at least point me in the right direction to a good tutorial?

int main() {
    cout << "Getting File Information..." << endl;
    ifstream file;
    char output[100];
    //int x;

    file.open("Numbers.txt", ios::in);    // open file

    cout << "Opened File Successfully ****************" << endl;
    file >> output;              // empty file contents into output
    cout << output;              // print out contents of file
    cout << "Should have printed out results by now" << endl;
    //file >> x;

    file.close();

    return 0;
}
+2  A: 

Visual Studio sets the working directory to YourProjectDirectory\Debug\Bin when running in debug mode. If your text file is in YourProjectDirectory, you need to account for that difference.

The easiest way to do that is to include your text files in the project and set their build action (in the Properties window) to Content.

Eric J.
You are talking about C# or VB.Net not C++
Cem Kalyoncu
A: 

Working path is project directory.

Cem Kalyoncu
At least in VS C++ 2005 and 6.0
Cem Kalyoncu
A: 

If you're talking about running the code within the Visual Studio debugger via F5 or Debug / Start Debugging, you can set the working directory of your program via Project / <Project name> Properties / Configuration / Debugging / Working directory.

Put your text file in a directory somewhere, and set Working directory to point to that directory.

RichieHindle
Never use an absolute path. It will break when moved to another computer.
Cem Kalyoncu
The Working Directory setting isn't stored in the project file anyway, so that's not an issue.
RichieHindle
Think of this way, you set working dir to c:\somedir and placed config files, move the program elsewhere it will not work *properly*
Cem Kalyoncu