OP 的代码不会检查他们的任何文件 IO 是否成功,因此文件可能尚未打开,文件可能为空,并且读取可能由于多种原因而失败。
幸运的是,getline 返回输入流,并且流实现了一个非常简洁的运算符 bool,如果流处于错误状态并且无法读取,则返回 false。如果无法读取文件,则 temp 的内容肯定是无效的,不应使用。
所以...
void readfile(vector<string> &filename)
{
string temp;
ifstream infile(filename[2].c_str());
if (getline (infile, temp)) //test the read for success
{
cout << temp << endl;
}
else
{
cout << "failed to read file" << endl;
}
}
如果 getline 由于任何原因失败,包括文件未打开、文件为空、文件损坏且无法读取,则流的状态将被标记为错误并在if() 检查时返回 false。
通常此时您应该检查错误的类型,infile.clear() 流以删除错误条件,然后收拾残局,但在这种情况下没有多大意义。如果您无法将文件的开头读入字符串,那么您就会遇到大问题,应该仔细查看文件 filename[2] 的运行状况和内容。
顺便说一下,如果你的编译器是最新的,ifstream 的构造函数会吃掉一个 std::string 并且ifstream infile(filename[2]); 将是有效的。
风格方面,最好将文件名字符串传递给 readfile,而不是向量。这使您可以将 readfile 函数重用于向量的元素 2 以外的地方。
void readfile(string & filename)
{
string temp;
ifstream infile(filename);
if (getline (infile, temp)) //test the read for success
{
cout << temp << endl;
}
else
{
cout << "failed to read file " << filename << endl;
}
}
并调用
readfile(filename[2]);
扩展此功能以实现 OP 的真正目标
void readfile(string & filename,
vector<string> & strings)
{
string temp;
ifstream infile(filename);
if (getline (infile, temp)) //test the read for success
{
strings.push_back(temp);
cout << temp << endl;
}
else
{
cout << "failed to read file " << filename << endl;
}
}
并调用
vector<string> strings;
...
readfile(filename[2], strings);