Back to C++
2026-03-147 min read

Example 2: C++ String to read a line of text

Learn Example 2: C++ String to read a line of text step by step with clear examples and exercises.

Why This Matters

In this lesson, we will delve into the essential skill of reading a line of text using C++ strings. Understanding this concept is crucial for developing user-friendly applications, as it enables us to read and process input from users effectively. Reading lines of text is an important step in creating interactive programs that can handle user inputs efficiently. Let's embark on an enlightening journey!

Prerequisites

Before diving in, it's essential that you are familiar with the following concepts:

  1. Basic C++ syntax and variables
  2. Basic I/O operations (std::cout, std::cin)
  3. Understanding of strings as a data type (std::string)
  4. Knowledge about standard libraries in C++ (`, `)
  5. Familiarity with control structures such as loops and conditionals
  6. Understanding of functions and their usage in C++
  7. Basic understanding of containers like maps and vectors
  8. Knowledge of string manipulation functions such as substr(), find(), and replace()
  9. Comfortable with exception handling (optional but recommended)

Core Concept

The std::string class in C++ offers a rich set of functions for manipulating and managing strings. One of the most important functions is std::getline(). This function reads a line from an input stream (usually std::cin) into a string.

Here's a simple example to illustrate its usage:

#include <iostream>
#include <string>

int main() {
std::string line;
std::getline(std::cin, line); // Read a line from the user
std::cout << "You entered: " << line << std::endl;
return 0;
}

In this example, we include the necessary libraries and define the main() function. Inside the function, we create an empty string variable called line. Then, we use std::getline() to read a line from the standard input (std::cin) and store it in the line variable. Finally, we print out the entered line using std::cout.

Input Delimiters

By default, std::getline() reads until it encounters a newline character (\n). However, you can specify a different delimiter by providing a second argument:

#include <iostream>
#include <string>

int main() {
std::string line;
std::getline(std::cin, line, ';'); // Read a line up to the semicolon character (';')
std::cout << "You entered: " << line << std::endl;
return 0;
}

In this example, we read a line from the user until we encounter a semicolon (;) instead of a newline.

String Streams

Another powerful tool for string manipulation in C++ is the std::istringstream. This class allows us to treat a string as an input stream and extract individual words or numbers. We'll explore its usage in more detail later in this lesson.

Splitting Strings

To split a string into words, you can use the std::string::split() function from the C++17 standard library:

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>

int main() {
std::string line = "This is a test";
std::vector<std::string> words;
std::copy(std::split(line, ' '), std::end(std::split(line, ' ')), std::back_inserter(words));
for (const auto& word : words) {
std::cout << word << " ";
}
return 0;
}

In this example, we split the input string line into words using a space as a delimiter and store them in a vector called words. We then iterate through the vector and print out each word.

Worked Example

Let's create a simple program that reads a line of text, counts the number of vowels, and prints out the result:

#include <iostream>
#include <string>
#include <map>

int main() {
std::string input;
std::getline(std::cin, input); // Read a line from the user

std::map<char, int> vowelCount; // Create a map to store vowel counts
vowelCount['A'] = 0;
vowelCount['E'] = 0;
vowelCount['I'] = 0;
vowelCount['O'] = 0;
vowelCount['U'] = 0;
vowelCount['a'] = 0;
vowelCount['e'] = 0;
vowelCount['i'] = 0;
vowelCount['o'] = 0;
vowelCount['u'] = 0;

for (char c : input) { // Iterate through each character in the input string
if (vowelCount.find(c) != vowelCount.end()) { // Check if the character is a vowel
++vowelCount[c]; // Increment the count for this vowel
}
}

std::cout << "The line contains the following number of vowels:" << std::endl;
for (const auto& pair : vowelCount) { // Iterate through the map and print out each vowel count
std::cout << pair.first << ": " << pair.second << std::endl;
}
return 0;
}

In this example, we first read a line of text from the user. Then, we create a map vowelCount to store the counts for each vowel. We initialize all counts to zero.

Next, we iterate through each character in the input string and check if it's a vowel by looking it up in the vowelCount map. If the character is found, we increment its count. After counting all vowels, we print out the results.

Common Mistakes

  1. Not including the necessary libraries: Remember to include `, `, and any other required libraries at the beginning of your code.
  2. Forgetting to include newline characters: When printing multiple lines, make sure to include a newline character (\n) after each line.
  3. Ignoring input delimiters: Be aware that std::getline() reads until it encounters the specified delimiter by default. If you want to read up to a specific character, make sure to specify it as the second argument.
  4. Not handling empty lines: If you're reading multiple lines of input, remember to handle cases where the user enters an empty line.
  5. Misunderstanding string streams: Understand that istringstream allows you to treat a string as a stream and extract individual words or numbers.
  6. Incorrectly handling vowels: Be aware that some programming conventions consider "y" both a consonant and a vowel, while others only count it as a vowel when used as such (e.g., in "about"). Make sure to handle "y" according to your chosen convention.
  7. Not properly handling exceptions: If an exception occurs during input or output operations, make sure to catch and handle it appropriately.
  8. Misusing string functions: Be aware of the differences between functions like substr(), find(), and replace() and use them accordingly.
  9. Not considering case sensitivity: Remember that C++ is case-sensitive, so you may need to convert characters to uppercase or lowercase when comparing or counting vowels.

Practice Questions

  1. Write a program that reads a line of text and counts the number of consonants in it.
  2. Write a program that reads multiple lines of text and prints out the lines containing only one word.
  3. Write a program that reads a line of text, replaces all occurrences of "apple" with "orange", and prints out the modified line.
  4. Write a program that reads a line of text, splits it into words, and sorts them in alphabetical order.
  5. Write a program that reads multiple lines of text and calculates the average word length.
  6. Write a program that reads a line of text, counts the number of occurrences of each letter (including uppercase and lowercase), and prints out the results.
  7. Write a program that reads a line of text, removes all duplicate words, and prints out the unique words in alphabetical order.
  8. Write a program that reads multiple lines of text, finds the longest word in each line, and prints out the longest word from all lines.
  9. Write a program that reads a line of text, counts the number of palindromes (words that read the same forwards and backwards), and prints out the count.
  10. Write a program that reads multiple lines of text, finds the most frequent word in each line, and prints out the most frequent word from all lines along with its frequency.

FAQ

  1. Why do we need to include library?

The ` library provides the necessary functions for handling strings in C++, such as std::getline()`.

  1. What is an istringstream and why do we use it?

An istringstream is a stream that reads from a string. It allows us to treat a string as a stream and extract individual words or numbers.

  1. Why does my program not read the entire line when using std::getline()?

Make sure you're not reading past the end of the line by specifying the correct delimiter (if necessary) and handling empty lines properly.

  1. How can I split a string into words in C++?

You can use the std::string::split() function from the C++17 standard library or manually iterate through the string using loops and find functions.

  1. What is the difference between std::string and char[] in C++?

Both std::string and char[] are used to store strings in C++. However, std::string provides additional functionality such as built-in functions for manipulating strings, while char[] requires manual memory management.

  1. How can I handle exceptions in C++?

You can use try-catch blocks to catch and handle exceptions that may occur during input or output operations.

  1. What are some common string manipulation functions in C++?

Some common string manipulation functions include substr(), find(), replace(), length(), compare(), and empty().

Example 2: C++ String to read a line of text | C++ | XQA Learn