Hey guys,
the following code snippet is from my textbook (section about file I/O):
Code:
// datacopy.cpp
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main() {
ifstream source;
string sFilename;
cout << "Source file: ";
cin >> sFilename;
source.open(sFilename.c_str(), ios::binary|ios::in);
if (!source) {
cerr << sFilename << " cannot be opened.\n";
exit(-1);
}
cout << "Target file: ";
string tFilename;
ofstream target(tFilename.c_str(), ios::binary|ios::out);
if (!target) {
cerr << tFilename << " cannot be opened.\n";
exit(-1);
}
char ch;
while (source.get(ch)) {
target.put(ch);
}
source.close();
target.close();
}
I typed it exactly like it is given in my textbook, but the program wouldn't even let me type in the target's file name.
I tried it with several different source file names, like test_file.txt, test_file, testfile, etc. Seems after typing in the source file name there is something remaining in the input buffer (the '\n'?), right?
Is this an error in the code snippet I should e-mail the author? Or am I wrong somewhere and don't see it myself?
EDIT: Here's an example output, just for clarification:
[dennis@marx k2]$ ./datacopy
Source file: datacopytest
Target file: cannot be opened.
[dennis@marx k2]$