Thread: ifstream/ofstream

  1. #1

    Post ifstream/ofstream

    #include <string>
    #include <fstream>
    using namespace std;

    int main() {
    ifstream in("Scopy.cpp"); // Open for reading
    ofstream out("Scopy2.cpp"); // Open for writing
    string s;
    while(getline(in, s)) // Discards newline char
    out << s << "\n"; // ... must add it back
    return 0;
    }


    in this short program I would like to know how the newline character is discarded in the while loop by using getline(in,s).

  2. #2
    of Zen Hall zen's Avatar
    Join Date
    Aug 2001
    Posts
    1,007
    '\n' is the default argument for the delimiter. If you don't specify your own, the newline will always be discarded.

    If you're just using streams to copy files, this is simpler -

    Code:
    #include <fstream> 
    using namespace std; 
    
    int main() { 
    
    	ifstream in("Scopy.cpp"); // Open for reading 
    	ofstream out("Scopy2.cpp"); // Open for writing 
    
    	out << in.rdbuf();
    
    	return 0; 
    }
    zen

  3. #3

    Post thanks

    THANKS!!!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. ifstream/ofstream to save variables
    By Donarstan in forum C++ Programming
    Replies: 4
    Last Post: 10-01-2008, 02:09 AM