Read a line with delimiter until the end of each line in C++

Learn how to read a line with delimiter until the end of each line in C++ with examples.

In this tutorial, you will see how to read a line using a delimiter. A delimiter specifies the boundary of in a line. We can use any character as a delimiter. e.g.

My name is Abhishek and I code.
// Lets assume our delimiter is ' '(space).

Therefore when we read the above line with ‘ ‘ (space) as a delimiter it will be:

My
name
is
Abhishek
and
I
code.

The line breaks when the ‘ ‘(space) delimiter is encountered. So let’s see how we can do this.

Using delimiters

For achieving this we will be using stringstream class. We will be picking string from a stream of strings whenever we encounter the delimiter. (‘\0’ is by default a delimiter).

stringstream   stream1(InputString);
// makes a stream of strings 'stream1' of InputString

Next, we will be using the getline() function:

string temp;
getline(stream1,temp,' ');
//temp stores string separated by delimiter(here space)

 

Below is the code to illustrate the example:

#include <bits/stdc++.h>
using namespace std;

int main() {
  string InputString ="My name is Abhishek and I code.";
  
  stringstream stream1(InputString);
  string temp;
  
  while(getline(stream1,temp,' ')){
      cout<<temp<<endl;
  }
  return 0;
}

Output:

My
name
is
Abhishek
and
I
code.

Here is another example using ‘/’ as a delimiter:

#include <bits/stdc++.h>
using namespace std;

int main() {
  string InputString ="If/I get/stuck/I go to CodeSpeedy";
  
  stringstream stream2(InputString);
  string temp;
  
  while(getline(stream2,temp,'/')){
      cout<<temp<<endl;
  }
  return 0;
}

Output:

If
I get
stuck
I go to CodeSpeedy

That’s all for this tutorial hope you understood it.

Also read: Take user input in map in C++

Leave a Reply

Your email address will not be published. Required fields are marked *