Search code examples
c++iofstream

stream does not append new line character


I call the function write in a loop. I need to append several lines.

I pass

std::fstream file(filename);

to

write(info, &file);

The following code doesn't append new line character, or at least Notepad++ does not display it.(i get just a whitespace) :

void IO::write(const std::string& name, std::iostream* stream)
{
    (*stream) << "usr" << name << " === " << "\n";
}

What is wrong? How to append the new line to the text file?


Solution

  • To elaborate on my rather harsh comment, there is nothing wrong with your newline, but...

    ...use the correct types...

    #include <iostream>
    #include <fstream>
    
    // ...
    std::ofstream file( filename );
    // ...
    

    ...and if you want to print info to the stream, just do it instead of going through some function...

    // ...
    file << "usr" << info << " === " << "\n";
    // ...
    

    ...if you really want to make it a function, at least use references and the proper types...

    void IO::write( std::ostream & stream, const std::string & name )
    {
        stream << "usr" << name << " === \n";
    }
    
    // ...
    IO::write( file, info );
    // ...
    

    ...but the "traditional" way of doing output in C++ is to overload the operator<< for the class in question, and have the implementation for printing an instance sit right alongside the class member implementations instead of going through C-style functions...

    class MyClass
    {
        // ...
        friend std::ostream & operator<<( std::ostream & stream, const MyClass & obj );
        // ...
    };
    
    std::ostream & operator<<( std::ostream & stream, const MyClass & obj )
    {
        stream << "usr" << obj.name << " ===\n";
        return stream;
    }
    
    // ...
    MyClass mine;
    file << "Hello\n" << mine << 42 << "\n";