I just found a way to copy a file with iterators to another file:
ifstream ifile("file1.txt");
ofstream ofile("file2.txt");
copy(istream_iterator<string>(ifile),
istream_iterator<string>(),
ostream_iterator<string>(ofile, " "));
It works, but unfortunately all text from “file1.txt” is in only one line at “file2.txt”, but oryginally at “file1.txt” are many lines.
I tried to change string between iterator’s loop:
copy(istream_iterator<string>(ifile),
istream_iterator<string>(),
ostream_iterator<string>(ofile, "\n"));
but result at “file2.txt” is worse – every word is in different line.
My question:
is any way to copy file with iterators but without loosing any informations, or should I do it with getline()?
istream_iterator<T> iter(stream)will use formatted input functions, so that++iteris somewhat equivalent to:For
stringobjects this means discarding any leading whitespace and reading only until the next whitespace character.If you want unformatted operations instead, use
istreambuf_iterator<char>(as was noted in the comments).