简体   繁体   中英

Copying words from one file to another in cpp

I'm trying to copy words from one file to another in cpp, here's my code :

int main()
{

    string from, to;

    cin >> from >> to;

    ifstream ifs(from);

    ofstream ofs(to);

    set<string> words(istream_iterator<string>(ifs), istream_iterator<string>());
    copy(words.begin(), words.end(), ostream_iterator<string>(ofs, "\n"));

    return !ifs.eof() || !ofs;
}

this way I get a compilation error :

expression must have class type

at the line of where I call copy()

If I change the construction of the iterators to the following it works :

set<string> words{ istream_iterator<string>{ ifs }, istream_iterator<string>{} };

I thought choosing between () and {} when initializing objects in cpp is just a matter of choice but I guess I'm wrong. Can someone explain this to me ?

In the first code snippet, the set<string> words(istream_iterator<string>(ifs), istream_iterator<string>()) line is parsed as a declaration of a function words that has two parameters: istream_iterator<string> ifs and an unnamed parameter of type istream_iterator<string> and returns a set<string> . That's why it gives a compilation error. The second one cannot be parsed as a function declaration, so it works properly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM