The very first C++ program you wrote probably looked something like this:
1 2 3 4 5 6 7 |
#include <iostream> int main() { std::cout << "Hello, world!\n"; return 0; } |
So what is “Hello, world!” exactly? “Hello, world!” is a collection of sequential characters called a string. In C++, we use strings to represent text such as names, addresses, words, and sentences. String literals (such as “Hello, world!\n”) are placed between double quotes to identify them as strings.
Because strings are commonly used in programs, most modern programming languages include a fundamental string data type. In C++, strings aren’t a fundamental type (they’re actually a compound type
, and defined in the C++ standard library rather than as part of the core language). But strings are straightforward and useful enough that we’ll introduce them here rather than wait until the chapter on compound types.
std::string
To use strings in C++, we first need to #include the <string> header to bring in the declarations for std::string. Once that is done, we can define variables of type std::string.
1 2 3 |
#include <string> // allows use of std::string std::string myName {}; // empty string |
Just like normal variables, you can initialize or assign values to strings as you would expect:
1 2 |
std::string myName{ "Alex" }; // initialize myName with string literal "Alex" myName = "John"; // assign variable myName the string literal "John" |
Note that strings can hold numbers as well:
1 |
std::string myID{ "45" }; // "45" is not the same as integer 45! |
In string form, numbers are treated as text, not numbers, and thus they can not be manipulated as numbers (e.g. you can’t multiply them). C++ will not automatically convert string numbers to integer or floating point values.
String input and output
Strings can be output as expected using std::cout:
1 2 3 4 5 6 7 8 9 10 |
#include <iostream> #include <string> int main() { std::string myName{ "Alex" }; std::cout << "My name is: " << myName << '\n'; return 0; } |
This prints:
My name is: Alex
However, using strings with std::cin may yield some surprises! Consider the following example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
#include <iostream> #include <string> int main() { std::cout << "Enter your full name: "; std::string name{}; std::cin >> name; // this won't work as expected since std::cin breaks on whitespace std::cout << "Enter your age: "; std::string age{}; std::cin >> age; std::cout << "Your name is " << name << " and your age is " << age << '\n'; return 0; } |
Here’s the results from a sample run of this program:
Enter your full name: John Doe Enter your age: Your name is John and your age is Doe
Hmmm, that isn’t right! What happened? It turns out that when using operator>> to extract a string from cin, operator>> only returns characters up to the first whitespace it encounters. Any other characters are left inside cin, waiting for the next extraction.
So when we used operator>> to extract a string into variable name, only “John” was extracted, leaving “Doe” inside std::cin, waiting for the next extraction. When we then used operator>> to get variable age, it extracted “Doe” instead of waiting for us to input an age. We are never given a chance to enter an age.
Use std::getline() to input text
To read a full line of input into a string, you’re better off using the std::getline() function instead. std::getline() takes two parameters: the first is std::cin, and the second is your string variable.
Here’s the same program as above using std::getline():
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
#include <string> // For std::string and std::getline #include <iostream> int main() { std::cout << "Enter your full name: "; std::string name{}; std::getline(std::cin, name); // read a full line of text into name std::cout << "Enter your age: "; std::string age{}; std::getline(std::cin, age); // read a full line of text into age std::cout << "Your name is " << name << " and your age is " << age << '\n'; return 0; } |
Now our program works as expected:
Enter your full name: John Doe Enter your age: 23 Your name is John Doe and your age is 23
Mixing std::cin and std::getline()
Reading inputs with both std::cin and std::getline may cause some unexpected behavior. Consider the following:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
#include <string> #include <iostream> int main() { std::cout << "Pick 1 or 2: "; int choice{}; std::cin >> choice; std::cout << "Now enter your name: "; std::string name{}; std::getline(std::cin, name); std::cout << "Hello, " << name << ", you picked " << choice << '\n'; return 0; } |
This program first asks you to enter 1 or 2, and waits for you to do so. All good so far. Then it will ask you to enter your name. However, it won’t actually wait for you to enter your name! Instead, it prints the “Hello” line, and then exits. What happened?
It turns out, when you enter a value using operator<<, std::cin not only captures the value, it also captures the newline character (‘\n’) that occurs when you hit the enter key. So when we type 2, std::cin actually gets the string “2\n”. It then extracts the 2 to variable choice
, leaving the newline character behind for later. Then, when std::getline() goes to read the name, it sees “\n” is already in the stream, and figures we must have entered an empty string! Definitely not what was intended.
A good rule of thumb is that after reading a value with std::cin, remove the newline from the stream. This can be done using the following:
1 |
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); |
If we insert this line directly after reading variable choice, the extraneous newline will be removed from the stream, and the program will work as expected!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
#include <iostream> #include <limits> #include <string> int main() { std::cout << "Pick 1 or 2: "; int choice{}; std::cin >> choice; // Remove the extraneous newline character so getline() doesn't think we entered an empty string std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); std::cout << "Now enter your name: "; std::string name{}; std::getline(std::cin, name); std::cout << "Hello, " << name << ", you picked " << choice << '\n'; return 0; } |
Rule
If reading values with std::cin and operator<<, it’s a good idea to remove the extraneous newline using std::cin.ignore().
String length
If we want to know how many characters are in a std::string is, we can ask the std::string for its length. The syntax for doing this is different than you’ve seen before, but is pretty straightforward:
1 2 3 4 5 6 7 8 9 |
#include <iostream> #include <string> int main() { std::string myName{ "Alex" }; std::cout << myName << " has " << myName.length() << " characters\n"; return 0; } |
This prints:
Alex has 4 characters
Note that instead of asking for the string length as length(myName)
, we say myName.length()
.
The length()
function isn’t a normal standalone function -- it’s a special type of function that belongs to std::string called a member function
. We’ll cover member functions, including how to write your own, in more detail later.
Conclusion
std::string is complex, leveraging many language features that we haven’t covered yet. Fortunately, you don’t need to understand these complexities to use std::string for simple tasks, like basic string input and output. We encourage you to start experimenting with strings now, and we’ll cover additional string capabilities later.
Quiz time
Question #1
Write a program that asks the user to enter their full name and their age. As output, tell the user how many years they’ve lived for each letter in their name (for simplicity, count spaces as a letter).
Sample output:
Enter your full name: John Doe Enter your age: 46 You've lived 5.75 years for each letter in your name.
![]() |
![]() |
![]() |
Leave a Reply