4

我试图编写一个代码来从名为“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
4

1 回答 1

8

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

(1) 你需要在周围加上引号test.txt

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

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

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

希望这可以帮助!

于 2013-06-22T02:24:21.630 回答