Replace comma with a new line in a text file using C++

In this tutorial, we will learn how to replace the comma with a new line in a text file using C++.

Before proceeding to the solution, let us learn about dealing with text files in C++ with a simple example:

C++ provides classes for file handling operations. They are, fstream, ifstream, and ofstream among which fstream handles both reading and writing files. The ifstream, defines the input file stream and is used for reading files while the ofstream, defines the output file stream and is used for writing data to files. The file handling operations include:

  1. Open: Creates a file, or opens an existing file.
  2. Read: Reads a file.
  3. Write: Writes data to a file.
  4. Close: Closes a file.

Syntax:

fstream filepointer;
filepointer.open(newfilename,ios::openmode)
filepointer.close()

There are also various file modes such as in, out, app, nocreate, noreplace, trunc, ate, binary, etc. We can use more than one mode at a time using pipes ‘|‘.

filepointer.open(newfilename,ios::in|ios::out);

Program to replace a comma with a new line in a text file using C++

#include <iostream>
#include<fstream>
using namespace std;
int main()
{
fstream nf,wf; 
nf.open("file1.txt",ios::out);  
if(!nf) 
{
cout<<"File cannot be created."<<endl;
}
else
{
    cout<<"New file is created."<<endl;
    nf<<"Happy,Coding.\n";
    nf.close(); 
}
nf.open("file1.txt",ios::in);   
wf.open("temporary.txt",ios::out);
if(!nf) 
{
    cout<<"No such file is created."<<endl;
    if(!wf)
    {
        cout<<"File cannot be created."<<endl;   
    }
} 
else 
{ 
    string a; 
    string a1="\n";
    int l,i;
    while (getline(nf,a)) 
    { 
    l=a.length();
    for(i=0;i<l;i++)
    {
    if(a[i]==',')
    {
    a.replace(i,1,a1);
    }
    }
    cout<<a<<endl;
    wf<<a;
    }
    nf.close();
    wf.close();
    remove("file1.txt");
    rename("temporary.txt","file1.txt");
}    
    return 0;
}

Output:

New file is created.
Happy
Coding.

file1.txt:

Happy
Coding.

This program creates a text file. It writes data into the file containing a comma. Then, it reads the same text file and replaces the comma with a new line in a text file using C++. For this, it reads a particular line in the file using getline() and then traces each of its characters to check if it is a comma. If the particular character is a comma, then replace it from that index to a new line character. Then print that line onto the terminal and write it to a temporary file. Then after the replacement of the entire file contents, remove the original file and rename the temporary file to the original file.

I hope this article was helpful. Thanks for reading!

Recommended Posts:
Tutorial: File Handling in C++
How to find substring from text file in C++

Leave a Reply

Your email address will not be published.