Back to C++
2026-02-057 min read

Example 1: C++ String to Read a Word

Learn Example 1: C++ String to Read a Word step by step with clear examples and exercises.

Title: Reading a Word from a C++ String: A full guide for Beginners

Why This Matters

You'll learn how to read a word from a C++ string. This skill is essential for handling user inputs, parsing data files, and working with text-based applications in C++. Understanding this concept can help you tackle real-world programming challenges, ace coding interviews, and debug common issues that arise when dealing with strings.

Prerequisites

Before diving into the core concept, it's important to ensure you have a good understanding of the following topics:

  1. C++ Basics: Variables, Data Types, Operators, Control Structures (if...else, for loops)
  2. Basic Input/Output: Using std::cin and std::cout to read from and write to the console
  3. Strings in C++: Understanding the standard library string class (std::string) and its basic operations such as accessing individual characters, finding positions of characters, and extracting substrings.
  4. File I/O: Basic knowledge of reading files using std::ifstream and writing to files using std::ofstream.

Core Concept

In C++, you can store text as a sequence of characters using strings. The standard library provides the std::string class for managing strings efficiently. To read a word from a string, we'll use various functions provided by the std::string class and other related libraries.

Accessing individual characters in a string

To access an individual character in a string, you can use square brackets ([]) with the index of the character you want to access. The first character has an index of 0.

#include <iostream>
#include <string>

int main() {
std::string myString = "Hello, World!";
char firstChar = myString[0]; // firstChar will contain 'H'
return 0;
}

Finding the position of a character in a string

To find the position (index) of a specific character within a string, you can use the find() function. This function returns the index of the first occurrence of the specified character, or std::string::npos if the character is not found.

#include <iostream>
#include <string>

int main() {
std::string myString = "Hello, World!";
int positionOfSpace = myString.find(' '); // positionOfSpace will contain 7 (index of the first space)
return 0;
}

Extracting a substring from a string

To extract a substring (a sequence of characters) from a string, you can use the substr() function. This function takes two arguments: the starting index and the length of the substring to be extracted.

#include <iostream>
#include <string>

int main() {
std::string myString = "Hello, World!";
std::string greeting = myString.substr(0, 5); // greeting will contain "Hello"
return 0;
}

Reading a word from the console and storing it in a string

To read a word from the console and store it in a string, you can use std::cin and the getline() function. This function reads a line of text from the input stream (in this case, the console) and stores it in the specified string, including spaces and newlines.

#include <iostream>
#include <string>

int main() {
std::string userInput;
std::getline(std::cin, userInput); // reads a word from the console and stores it in userInput
return 0;
}

To read a single word without spaces or newlines, you can use std::getline() with an additional argument to specify the maximum number of characters to read.

#include <iostream>
#include <string>

int main() {
std::string userInput;
getline(std::cin, userInput, ' '); // reads a word from the console and stores it in userInput up to the first space character
return 0;
}

Reading multiple words from the console and storing them in a string vector

To read multiple words from the console and store them in a std::vector, you can use a loop and std::getline().

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

int main() {
std::vector<std::string> words;
std::string word;
while (std::getline(std::cin, word)) {
words.push_back(word);
}
return 0;
}

Worked Example

In this example, we will read a word from the console, store it in a string, and then print its length.

#include <iostream>
#include <string>

int main() {
std::string userInput;
std::getline(std::cin, userInput); // reads a word from the console and stores it in userInput
int lengthOfWord = userInput.length(); // calculates and stores the length of the word in lengthOfWord
std::cout << "The length of your word is: " << lengthOfWord << std::endl;
return 0;
}

Common Mistakes

  1. Forgetting to include the necessary headers (`, `)
  2. Misunderstanding string indices: starting at 0, not 1
  3. Using std::cin >> word instead of std::getline(std::cin, word) for reading a word from the console
  4. Not checking if the specified character is actually present in the string before using find() or substr() functions
  5. Forgetting to include semicolons at the end of statements
  6. Using std::cin with getline() to read multiple lines from the console without considering newlines as part of the input
  7. Not properly handling exceptions when reading files using std::ifstream and std::ofstream
  8. Forgetting to close files after reading or writing operations

Practice Questions

  1. Write a program that reads two words from the console, stores them in separate strings, and then prints their concatenation (i.e., the combination of both words).
  2. Write a program that reads a line containing multiple words separated by spaces, extracts each word using std::getline(), and stores them in a vector of strings.
  3. Write a program that reads a string from the console, finds the position of the first occurrence of the letter 'a', and prints all occurrences of 'a' in the string.
  4. Write a program that reads a line containing multiple words separated by spaces, removes duplicates, and prints the unique words in alphabetical order.
  5. Write a program that reads a file named input.txt, reads each word from the file, stores them in a vector of strings, and then writes the content to another file named output.txt.
  6. Write a program that reads a line containing multiple words separated by spaces, sorts the words in reverse alphabetical order, and prints the sorted words.
  7. Write a program that reads a line containing multiple words separated by spaces, replaces all occurrences of the word "World" with the word "Earth".
  8. Write a program that reads a file named input.txt, finds the most frequently occurring word in the file, and prints its count along with the word.
  9. Write a program that reads two files named file1.txt and file2.txt, merges their contents into a single string, and then writes the merged content to a new file named merged.txt.
  10. Write a program that reads a line containing multiple words separated by spaces, checks if any word is longer than 10 characters, and prints the long words.

FAQ

Q: Why can't I use std::cin >> word to read a whole word from the console?

A: Because whitespace characters (spaces, tabs, newlines) are treated as separators by >>. To read an entire word without spaces or newlines, you should use std::getline(std::cin, word, ' ').

Q: What happens if I try to access a character index that is out of bounds in a string?

A: If you attempt to access a character index that is beyond the end of the string, your program will likely crash or exhibit unpredictable behavior. To avoid this, always check if an index falls within the valid range before accessing it.

Q: Can I use std::cin with getline() to read multiple lines from the console?

A: Yes! You can use a loop to repeatedly call std::getline(std::cin, line) until you reach the end of input (i.e., when std::cin.eof() returns true). However, be aware that newlines are part of the input and will be included in the lines read unless you specify a delimiter.

Q: How can I handle exceptions when reading files using std::ifstream and std::ofstream?

A: You can use try-catch blocks to catch exceptions that may occur during file operations, such as file not found or permission denied errors.

Q: How do I properly close files after reading or writing operations in C++?

A: To properly close a file, you should call the close() function on the associated file stream object (e.g., fileStream.close()). It's also good practice to use a std::ofstream object with automatic resource management (ARM) by wrapping it in an std::unique_ptr.

Q: What is the difference between std::getline(std::cin, word) and std::getline(std::cin, line, '\n')?

A: The first version reads a line up to the end of input (including newlines), while the second version reads a line up to the specified delimiter ('\n', newline character).

Example 1: C++ String to Read a Word | C++ | XQA Learn