调试输出:
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/