c++ - VS C++ 程序仅在从文件夹运行 .exe 时才有效? [不是VS调试]

标签 c++ visual-studio-2008 debugging exe

调试输出:

File opened...

File contents:

.exe 的输出(通过双击/project/debug 运行):

File opened...

File contents: line1 line2 etc. . .

源代码:

#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;
}

谢谢你的帮助!

我现在明白问题所在了,谢谢。显然,这也说明了这种对文件进行错误处理的方法是毫无值(value)的。我也纠正了这一点。再次感谢。

最佳答案

你对这一行的编码方式:

ifstream myFile("test_data.txt");

表示代码正在当前工作目录中查找文件。

当您在将是 /project/debug 的调试器之外运行时(在您的情况下),这可能是文件所在的位置。

当您在调试器中运行时(可能)是 \project,其中不包含该文件。

您需要拥有该文件的两份拷贝、对文件的完整路径进行硬编码,或者通过某种方式在运行时指定文件。

关于c++ - VS C++ 程序仅在从文件夹运行 .exe 时才有效? [不是VS调试],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1354985/

相关文章:

c++ - 如何使用 boost 从 C++ 中的 json 中读取枚举?

asp.net - Visual Studio 2008 中的解决方案加载缓慢

mysql - 如何在 MS Visual Studio 2008 上从 VC++ 连接 MySQL?

c++ - unsigned int 和 double 转换顺序

尝试重新排列数组时 C++ 程序崩溃

c++ - 我应该在主函数内部还是外部声明一个变量?

xml - Visual Studio 2008 自定义配置 xsd intellisense 自动完成损坏!

python - 如何在 python 中恢复旧的回溯? (例如倒数第二个)

c# - 从不同的线程调试

C - 如何在 Xcode 的调试器中将指向字符串数组的指针视为数组