adding a newline to file in C++

前端 未结 3 2019
自闭症患者
自闭症患者 2020-12-19 21:29

Can any body help me with this simple thing in file handling?

The following is my code:

#include
#include
using namesp         


        
相关标签:
3条回答
  • 2020-12-19 22:15

    First, you need to open the stream to write to a file:

    ofstream file; // out file stream
    file.open("anish.txt");
    

    After that, you can write to the file using the << operator:

    file << "hi this is first program i writer";
    

    Also, use std::endl instead of \n:

    file << "hi this is first program i writer" << endl << "this is an experiment";
    
    0 讨论(0)
  • 2020-12-19 22:30
    #include <fstream>
    using namespace std;
    
    int main(){
     fstream file;
     file.open("source\\file.ext",ios::out|ios::binary);
     file << "Line 1 goes here \n\n line 2 goes here";
    
     // or
    
     file << "Line 1";
     file << endl << endl;
     file << "Line 2";
     file.close();
    }
    

    Again, hopefully this is what you want =)

    0 讨论(0)
  • 2020-12-19 22:31
    // Editor: MS visual studio 2019
    // file name in the same directory where c++ project is created
    // is polt ( a text file , .txt)
    //polynomial1 and polynomial2 were already written
    //I just wrote the result manually to show how to write data in file
    // in new line after the old/already data
    #include<iostream>
    #include<string>
    #include<fstream>
    using namespace std;
    int main()
    {
        fstream file;
        file.open("poly.txt", ios::out | ios::app);
        if (!file) {
            cout << "File does not exist\n";
        }
        else
        {
            cout << "Writing\n";
                file << "\nResult: 4x4 + 6x3 + 56x2 + 33x1 + 3x0";  
        }
        system("pause");
        return 0;
    }
    
    **OUTPUT:** after running the data in the file would be
    polynomial1: 2x3 + 56x2-1x1+3x0
    polynomial2: 4x4+4x3+34x1+x0
    Result: 4x4 + 6x3 + 56x2 + 33x1 + 3x0
    The code is contributed by Zia Khan
    
    0 讨论(0)
提交回复
热议问题