【发布时间】:2017-11-15 07:38:35
【问题描述】:
我有一个输入文件“abc.txt”,其中每一行都包含用“,”分隔的字符。 尝试使用 ifstream 逐行读取文件时,它无法读取文件,我在控制台上得到的输出为“无法打开输入文件。”。 我究竟做错了什么? 代码:-
void EnterFiles(string filename, int index)
{
string line;
vector<string> f1,f2;
std::ifstream f;
//prepare f to throw if failbit gets set
std::ios_base::iostate exceptionMask = f.exceptions() | std::ios::failbit;
f.exceptions(exceptionMask);
try
{
f.open(filename);
}
catch (std::ios_base::failure& e)
{
std::cerr << e.what() << '\n';
}
if (!f)
{
cout << "Cannot open input file.\n";
}
while (getline(f,line) )
{
if (index == 0)
{
f1.push_back(line);
cout << line << endl;
}
else
{
f2.push_back(line);
cout << line << endl;
}
}
f.close();
}
【问题讨论】:
-
使用文件的完整路径名。
-
你没有给出你的文件路径,你的文件和你的程序在同一个目录吗?如果没有,你必须给它正确的路径。
-
你应该尝试打印原因:stackoverflow.com/questions/17337602/…
-
使用该路径,您需要从与文件相同的目录运行程序。你是如何运行你的程序的?
-
包含exe的文件夹不一定是当前工作目录。