Tutorialspoint
Problem
Solution
Submissions

Count the Number of Lines in Input

Certification: Basic Level Accuracy: 66.67% Submissions: 12 Points: 10

Write a C++ program that counts the number of lines in the input. The program should take input from the user and return the number of lines.

Example 1
  • Input: string = "Hello\nWorld\nC++"
  • Output: 3
  • Explanation:
    • Step 1: Initialize a line counter to 1 (assuming at least one line exists).
    • Step 2: Initialize a pointer to the start of the input string.
    • Step 3: Iterate through each character of the string using the pointer.
    • Step 4: For each character, check if it's a newline character ('\n').
    • Step 5: If a newline character is found, increment the line counter.
    • Step 6: Return the line count (3 lines).
Example 2
  • Input: string = "One\nTwo\nThree\nFour\nFive"
  • Output: 5
  • Explanation:
    • Step 1: Initialize a line counter to 1 (assuming at least one line exists).
    • Step 2: Initialize a pointer to the start of the input string.
    • Step 3: Iterate through each character of the string using the pointer.
    • Step 4: For each character, check if it's a newline character ('\n').
    • Step 5: If a newline character is found, increment the line counter.
    • Step 6: Return the line count (5 lines).
Constraints
  • Input size ≤ 10^6 characters
  • Input contains printable ASCII characters
  • Time Complexity: O(n) where n is the number of characters in the input
  • Space Complexity: O(1)
StringsFunctions / MethodsFile Handling IBMSamsung
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use string stream to handle input instead of file handling.
  • Count the number of newline characters in the input.
  • Return the count as the number of lines.

Steps to solve by this approach:

 Step 1: Define a function countLines that takes a constant string reference as parameter.

 Step 2: Create an input string stream with the provided string.
 Step 3: Initialize a line counter to zero.
 Step 4: Use getline in a while loop to read each line from the stream.
 Step 5: Increment the line counter for each successful read.
 Step 6: Return the final line count.
 Step 7: In main, prompt the user to enter multi-line content.
 Step 8: Read all input lines into a string, appending a newline after each line.
 Step 9: Call countLines with the full input string and print the result.

Submitted Code :