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 ?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With