在C ++中向文件添加换行符

时间:2011-03-21 04:21:39

标签: c++ file-io

在文件处理方面,任何人都可以帮我解决这个简单的问题吗?

以下是我的代码:

#include<iostream>
#include<fstream>
using namespace std;
int main()
{
  ofstream savefile("anish.txt");
 savefile<<"hi this is first program i writer" <<"\n this is an experiment";
 savefile.close();
  return 0 ;
 }

现在它已成功运行,我想按照我的方式格式化文本文件的输出。

我有:

  
    

这是第一个程序我作家这是一个实验

  

如何使输出文件如下所示:

  
    

这是第一个程序

         

我作家这是一个实验

  

如何以这种方式格式化输出?

3 个答案:

答案 0 :(得分:11)

#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();
}

再次,希望这是你想要的=)

答案 1 :(得分:1)

首先,您需要打开流以写入文件:

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

之后,您可以使用<<运算符写入文件:

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

另外,请使用std::endl代替\n

file << "hi this is first program i writer" << endl << "this is an experiment";

答案 2 :(得分:-1)

// 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