Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copying words from one file to another in cpp

Tags:

c++

file

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 ?

like image 291
dikson231 Avatar asked Feb 12 '15 17:02

dikson231


People also ask

How do you copy one file to another?

You can also copy files using keyboard shortcuts by following these steps. Highlight the files you want to copy. Press the keyboard shortcut Command + C . Move to the location you want to move the files and press Command + V to copy the files.


1 Answers

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.

like image 115
kraskevich Avatar answered Sep 27 '22 19:09

kraskevich