Storage for variable length text must be different from the fixed array of characters provided by our previous example. That storage is provided by std::string.
#include <iostream>
#include <string>
int main()
{
std::string name;
name = "Vitalik";
std::cout << name << '\n';
return 0;
}
The initial statement creates an empty std::string object named name, so no characters are stored inside it. The following statement replaces those empty contents with the four characters from the string literal "Vitalik". This assignment works because std::string knows how to copy characters from a string literal.
The subsequent std::cout statement then prints those four characters, followed by a newline. This is the end of the program, and it will compile and print:
VitalikA string can also be initialized with its characters at the moment it is created.
#include <iostream>
#include <string>
int main()
{
std::string greeting{"Hello"};
std::cout << greeting << '\n';
return 0;
}
The braces following the variable name indicate which characters should initially be placed inside the string, so the variable greeting starts with the five characters in "Hello". The print statement displays them exactly as they are. Using braces makes the initialization clear and avoids the need for a separate assignment statement.
Reading text from the keyboard introduces a small difficulty because the usual extraction operator stops at the first whitespace character.
#include <iostream>
#include <string>
int main()
{
std::string first;
std::cin >> first;
std::cout << first << '\n';
return 0;
}
Suppose the user types John Doe and presses Enter. The extraction operator reads only John into first because the space acts as a delimiter. The rest of the line, which contains a space followed by Doe, remains in the input stream. The program therefore outputs:
John
To read an entire line that may include whitespace, it is necessary to use std::getline.
#include <iostream>
#include <string>
int main()
{
std::string full_name;
std::getline(std::cin, full_name);
std::cout << full_name << '\n';
return 0;
}
The function std::getline reads characters from the stream until it finds a newline. Everything before that newline, but not the newline itself, is stored inside full_name. If the user types John Doe, the entire phrase is stored in the string, and the print statement outputs John Doe. The newline is consumed and discarded, leaving the input buffer ready for the next operation.
Mixing input from the extraction operator with std::getline will often result in an empty string being read by std::getline.
#include <iostream>
#include <string>
int main()
{
std::string word;
std::string line;
std::cin >> word;
std::getline(std::cin, line);
std::cout << word << '\n';
std::cout << line << '\n';
return 0;
}
Suppose the user enters hello and presses Enter. The extraction operator reads hello into word, but leaves the newline in the input buffer. When std::getline is called on the next line, it immediately finds that leftover newline, stores nothing inside line, and finishes.
The first output statement prints hello, while the second prints a blank line. This is not a bug in std::getline, but a direct result of the newline left behind by the previous extraction operation.
The length() member function returns the current number of characters stored in a string.
#include <iostream>
#include <string>
int main()
{
std::string text{"sample"};
std::cout << text.length() << '\n';
return 0;
}
The string text contains six characters. Calling text.length() returns 6, which is then printed by std::cout. This size does not include a terminating null character because std::string keeps track of its own length. An empty string reports a length of 0.
Two strings can be combined using the + operator or the append() member function.
#include <iostream>
#include <string>
int main()
{
std::string first{"Good"};
std::string second{" morning"};
std::string result = first + second;
std::cout << result << '\n';
return 0;
}
first contains the four characters in Good, while second contains a space followed by the seven characters in morning. When the two strings are added together, a new string containing all twelve characters is created and assigned to result. The print statement therefore outputs Good morning, while the original strings remain unchanged.
All of the programs above are complete and can be compiled and executed. Each one performs a single useful task, including creating an empty string and assigning text to it, initializing a string when it is declared, reading one word, reading an entire line, understanding the interaction between the two input methods, checking the current length of a string, and joining two strings.
Exercise: Working with std::stringStarter code, hints and solutionOpenClose
Practice: Working with std::string
Work through the mission, reveal hints only when needed, and compare your result with the model solution.
Your challenge
Use red apple on one input line. Label word and line inside brackets so any leading space is visible, and explain what remains for getline after extraction.
Mission checklist
- Run the starter as a baseline, then predict the change requested in Your challenge.
- Make that change in your editor; use the lesson-specific hints if you need help.
- Compile and run your answer, then compare with the worked solution and explain the result.
Starter program
This is the working baseline, not the completed answer. Compile as C++20, then make the change described above.
#include <iostream>
#include <string>
int main()
{
std::string word;
std::string line;
std::cin >> word;
std::getline(std::cin, line);
std::cout << word << '\n';
std::cout << line << '\n';
return 0;
}Hints
operator>> reads only the next word into word and leaves the following separator in the stream. getline then reads the remainder of that same line into line.
Try typing "red apple" on one line, then try a single word followed by Enter. Notice the leading space in one remainder and the empty remainder in the other.
Worked solution
For the input red apple, extraction stores red in word. getline then stores the remaining leading space and apple in line. The added bracketed labels reveal that space; the second string is not read from a fresh input line.
#include <iostream>
#include <string>
int main()
{
std::string word;
std::string line;
std::cin >> word;
std::getline(std::cin, line);
std::cout << "word = [" << word << "]\n";
std::cout << "line = [" << line << "]\n";
return 0;
}
Example input
red apple
Example output
Program output only; your terminal may also echo the input you type.
word = [red]
line = [ apple]
0 comments
No comments yet. Be the first.