gpt4 book ai didi

c++ - Getline 只返回空白

转载 作者:行者123 更新时间:2023-11-28 06:00:35 25 4
gpt4 key购买 nike

我试图连续打开多个文件。文件名都存储在一个 vector 中,传递给我的函数。这只是一个简单的测试,以确保一切正常。如果它有效,那么我将需要将文件包含的任何内容推回到另一个 vector 中。

void readfile(vector<string> &filename)
{
string temp;
ifstream infile(filename[2].c_str());
getline (infile, temp);
cout << temp << endl;
}

这只是输出一个空行,尽管文本文件包含一段信息。我有一段时间没有使用文件 I/O,所以我有点生疏了。任何帮助表示赞赏。

编辑:你们都提供了很大的帮助,还有一件事,我需要在没有句点或空格的情况下传递它们。基本上只是一串字符。

最佳答案

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,而不是 vector 。这允许您重用 readfile 函数,而不仅仅是 vector 的元素 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);

关于c++ - Getline 只返回空白,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33356615/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com