views:

140

answers:

3

Output from debug:

File opened...

File contents:

Output from .exe (run via double click from /project/debug):

File opened...

File contents: line1 line2 etc. . .

Source code:

#include <iostream>
#include <fstream>
#include <regex>
#include <string>
#include <list>

using namespace std;
using namespace tr1;


int main()
{
    string line;
    list<string> dataList;

    ifstream myFile("test_data.txt");
    if (! myFile)
    {
     cout << "Error opening file. \n";
     return 0;
    }
    else
    {
     cout << "File opened... \n";
     while( getline(myFile, line) ) {
      dataList.push_back(line);
     }
    }

    cout << "\n\n File contents:";

    list<string>::iterator Iterator;
    for(Iterator = dataList.begin(); 
      Iterator != dataList.end();
      Iterator++)
    {
     cout << "\t" + *Iterator + "\n";
    }




    getchar();
    return 1;
}

thank you for your help!

i now understand the problem, thank you. obviously, this also shows that this method of error handling for files is worthless. I have corrected that as well. Thanks again.

+4  A: 

The way you've coded this line:

ifstream myFile("test_data.txt");

means that the code is looking for the file in the current working directory.

When you run outside the debugger that will be /project/debug (in your case), which is where the file presumably is.

When you run inside the debugger that will (probably) be \project, which won't contain the file.

You'll need to either have two copies of the file, hard code the full path to the file, or have some way of specifying the file at runtime.

ChrisF
+1  A: 

Your .exe is normally run from Debug/../ when started from Visual Studio. When you double-click on it, it runs in 'Debug/'.

Either move your test_data.txt, or do as most developers and create an output directory where your binaries and data are exported before run.

Jonas Byström
+2  A: 

You can also specify the working directory (where it will look for test_data.txt) in the Debug property page for your project in VC.

Alan