Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • C++ Data Types
  • C++ Input/Output
  • C++ Arrays
  • C++ Pointers
  • C++ OOPs
  • C++ STL
  • C++ Interview Questions
  • C++ Programs
  • C++ Cheatsheet
  • C++ MCQ
  • C++ Projects
  • C++ Exception Handling
  • C++ Memory Management
Open In App
Next Article:
How to Take Input in Array in C++?
Next article icon

How to use getline() in C++ when there are blank lines in input?

Last Updated : 03 Jun, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

In C++, if we need to read a few sentences from a stream, the generally preferred way is to use the getline() function as it can read string streams till it encounters a newline or sees a delimiter provided by the user. Also, it uses <string.h> header file to be fully functional.

Here is a sample program in c++ that reads four sentences and displays them with ": newline" at the end 

CPP
// A simple C++ program to show working of getline #include <cstring> #include <iostream> using namespace std; int main() {     string str;     int t = 4;     while (t--) {         // Read a line from standard input in str         getline(cin, str);         cout << str << " : newline" << endl;     }     return 0; } 

Sample Input :

 This  is  Geeks  for

As the expected output is:

This : newline is  : newline Geeks : newline for : newline

The above input and output look good, there may be problems when the input has blank lines in between. 

Sample Input :

This  is   Geeks  for

Output:

This : newline  : newline is  : newline  : newline

It doesn't print the last 3 lines. The reason is that getline() reads till enter is encountered even if no characters are read. So even if there is nothing in the third line, getline() considers it as a single line. Further, observe the problem in the second line. The code can be modified to exclude such blank lines. Modified code: 

CPP
// A simple C++ program that uses getline to read // input with blank lines #include <cstring> #include <iostream> using namespace std; int main() {     string str;     int t = 4;     while (t--) {         getline(cin, str);          // Keep reading a new line while there is         // a blank line         while (str.length() == 0)             getline(cin, str);          cout << str << " : newline" << endl;     }     return 0; } 

Input:

This  is   Geeks  for

Output:

This : newline is  : newline Geeks : newline for : newline


Next Article
How to Take Input in Array in C++?

S

Sarin Nanda
Improve
Article Tags :
  • C Language
  • C++
  • CPP-Library
  • cpp-input-output
Practice Tags :
  • CPP

Similar Reads

  • How to Take Input in Array in C++?
    Arrays in C++ are derived data types that can contain multiple elements of the same data type. They are generally used when we want to store multiple elements of a particular data type under the same name. We can access different array elements using their index as they are stored sequentially in th
    3 min read
  • How to Read and Print an Integer value in C++
    The given task is to take an integer as input from the user and print that integer in C++ language. In this article, we will learn how to read and print an integer value. In the below program, the syntax and procedures to take the integer as input from the user is shown in C++ language. Standard Inp
    2 min read
  • Reading Lines by Lines From a File to a Vector in C++ STL
    Prerequisites: STL in C++Vector in C++File handling in C++ The Standard Template Library (STL) is a set of C++ template classes to provide common programming data structures and functions such as lists, stacks, arrays, etc. It is a library of container classes, algorithms, and iterators. Vector in C
    2 min read
  • How to split a string in C/C++, Python and Java?
    Splitting a string by some delimiter is a very common task. For example, we have a comma-separated list of items from a file and we want individual items in an array. Almost all programming languages, provide a function split a string by some delimiter. In C: // Splits str[] according to given delim
    7 min read
  • Find sum of integers in a file which contains any characters
    You are given a text file which contains any type of characters. You have to find the sum of integer values. Examples: Input : text.txt Let contents of test.txt be : :-,,$%^5313&^*1)(*( 464sz29>>///11!!! (*HB%$#)(*0900 Output : 6727 Input : text1.txt Let contents of test.txt be : 234***3r3
    2 min read
  • lseek() in C/C++ to read the alternate nth byte and write it in another file
    From a given file (e.g. input.txt) read the alternate nth byte and write it on another file with the help of “lseek”. lseek (C System Call): lseek is a system call that is used to change the location of the read/write pointer of a file descriptor. The location can be set either in absolute or relati
    2 min read
  • std::basic_istream::getline in C++ with Examples
    The std::basic_istream::getline is used to extract the characters from stream until end of line or the extracted character is the delimiting character. The delimiting character is the new line character i.e '\n'. This function will also stop extracting characters if the end-of-file is reached if inp
    2 min read
  • Set Position with seekg() in C++ File Handling
    seekg() is a function in the iostream library that allows you to seek an arbitrary position in a file. It is included in the <fstream> header file and is defined for istream class. It is used in file handling to sets the position of the next character to be extracted from the input stream from
    3 min read
  • How to write long strings in Multi-lines C/C++?
    Image a situation where we want to use or print a long long string in C or C++, how to do this? In C/C++, we can break a string at any point in the middle using two double quotes in the middle. Below is a simple example to demonstrate the same. C/C++ Code #include<stdio.h> int main() { // We c
    2 min read
  • list::front() and list::back() in C++ STL
    Lists are containers used in C++ to store data in a non-contiguous fashion, Normally, Arrays and Vectors are contiguous in nature, therefore the insertion and deletion operations are costlier as compared to the insertion and deletion option in Lists. list::front() This function is used to reference
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences