我尝试编写代码来从名为“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
答案 0 :(得分:8)
这里有(我相信)两个错误:
(1)你需要在test.txt
附近加上引号:
istream_iterator<string>(ifstream("test.txt"), ... );
(2)istream_iterator
的构造函数接受istream&
(即对流的左值引用)。因此,您传入的流必须是左值。但是,传入ifstream("test.txt")
传递的是ifstream
类型的临时对象,它是 rvalue 而不是左值。这与你不能这样做的原因相同:
int function(int& x) {
x++;
}
int main() {
function(137); // Error - 137 is an rvalue, but lvalue is needed.
}
希望这有帮助!