gpt4 book ai didi

c++ - 为什么 istream_iterator(ifstream ("test.txt")) 会导致错误?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:23:55 26 4
gpt4 key购买 nike

我尝试编写代码从名为“test.txt”的文件中读取字符串并将字符串写入标准输出。下面的代码运行良好:

 int main()
{
using namespace std;
ifstream file("test.txt");
copy(istream_iterator<string>(file),
istream_iterator<string>(),
ostream_iterator<string>(cout, " "));
}

但是,通过此修改,代码不再编译:

   int main()
{
using namespace std;
copy(istream_iterator<string>(ifstream("test.txt")), // <-- Error here
istream_iterator<string>(),
ostream_iterator<string>(cout, " "));
}

为什么这个版本不能编译?

我用的编译器是g++4.6.2,报错如下:

ex11-16.cpp:16:65: error: no matching function for call to 'std::istream_iterator<std::basic_string<char> >::istream_iterator(std::ifstream)'
ex11-16.cpp:16:65: note: candidates are:
.../bits/stream_iterator.h:72:7: note: std::istream_iterator<_Tp, _CharT, _Traits, _Dist>::istream_iterator(const std::istream_iterator<_Tp, _CharT, _Traits, _Dist>&) [with _Tp = std::basic_string<char>, _CharT = char, _Traits = std::char_traits<char>, _Dist = int, std::istream_iterator<_Tp, _CharT, _Traits, _Dist> = std::istream_iterator<std::basic_string<char> >]
.../bits/stream_iterator.h:72:7: note: no known conversion for argument 1 from 'std::ifstream {aka std::basic_ifstream<char>}' to 'const std::istream_iterator<std::basic_string<char> >&'
.../bits/stream_iterator.h:68:7: note: std::istream_iterator<_Tp, _CharT, _Traits, _Dist>::istream_iterator(std::istream_iterator<_Tp, _CharT, _Traits, _Dist>::istream_type&) [with _Tp = std::basic_string<char>, _CharT = char, _Traits = std::char_traits<char>, _Dist = int, std::istream_iterator<_Tp, _CharT, _Traits, _Dist>::istream_type = std::basic_istream<char>]
.../bits/stream_iterator.h:68:7: note: no known conversion for argument 1 from 'std::ifstream {aka std::basic_ifstream<char>}' to 'std::istream_iterator<std::basic_string<char> >::istream_type& {aka std::basic_istream<char>&}'
.../bits/stream_iterator.h:64:26: note: std::istream_iterator<_Tp, _CharT, _Traits, _Dist>::istream_iterator() [with _Tp = std::basic_string<char>, _CharT = char, _Traits = std::char_traits<char>, _Dist = int]
.../bits/stream_iterator.h:64:26: note: candidate expects 0 arguments, 1 provided

最佳答案

这里(我相信)有两个错误:

(1) 你需要在test.txt两边加上引号:

istream_iterator<string>(ifstream("test.txt"), ... );

(2) istream_iterator 的构造函数接收一个istream&(即对流的左值引用)。因此,您传入的流必须是左值。但是,传入 ifstream("test.txt") 会传入一个类型为 ifstream 的临时对象,它是一个 rvalue 而不是 < em>左值。这与您不能这样做的原因相同:

int function(int& x) {
x++;
}
int main() {
function(137); // Error - 137 is an rvalue, but lvalue is needed.
}

希望这对您有所帮助!

关于c++ - 为什么 istream_iterator<string>(ifstream ("test.txt")) 会导致错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17246720/

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