1. Goals
Use
std::stringto store a full name and build a greeting.Choose between reading a whole line and reading a number.
Check for failed input before using the data.
2. Prerequisites
You know variables, conditions, functions, and return. Examples use C++17
with explicit types. You do not need manual allocation or string internals.
3. Explanation
std::string, from <string>, stores a sequence of char elements. You can
initialize std::string name = "An";, assign another name, or concatenate
strings using +. The declaration std::string name; creates an empty string.
This differs from an uninitialized local int, which you must not read before
assigning a value. In "Hello, " + name + "!", a std::string operand makes
concatenation available. Two string literals, such as "Hello" + "An", do
not support that operation by themselves; start with a std::string value.
name.empty() tells you whether the string is empty. name.size() counts
char elements, not human-visible characters. For UTF-8 text, this is a byte
count; a Vietnamese letter can occupy several bytes. The example therefore
prints the label Bytes and uses an ASCII name for a predictable result.
Do not use that count to cut through a Unicode character.
See the string size rules.
std::cin >> name reads one word and stops at whitespace. To keep a full
name, use std::getline(std::cin, name): it reads until a newline and removes
that delimiter from the stream without adding it to the string. An empty
line produces an empty string; this example deliberately rejects it.
Spaces within the name are preserved.
See the string input rules.
std::cin >> age attempts to read an integer. !(std::cin >> age) indicates
failure, for example with abc, a value outside the type's range, or the end
of input before a number. EOF means no more input is available; it is neither
the number 0 nor an empty line. The example exits with status 1 when data
is missing. Do not use the attempted result without checking the read.
A successful read can still violate the requirements: age -2 is an integer
but outside the permitted range 0–130. Also, >> can consume only a
prefix: 18abc yields 18 and leaves abc behind. This lesson demonstrates
formatted input; the next practice lesson validates an entire input line.
If you read a number before calling getline, the remaining newline can
make getline immediately produce an empty string. After checking that the
number was read successfully, you can use
std::getline(std::cin >> std::ws, name) and check that operation too.
std::ws removes all leading whitespace, including multiple empty lines
and spaces before the name; it does not merely remove one newline. Use this
when discarding them is intended. To preserve empty lines or leading spaces,
read each line with getline and process it separately, as in the next lesson.
See the behavior of std::ws.
4. Runnable example
Save as main.cpp and compile with C++17. This program reads the name before
the age, avoiding a newline left over by numeric extraction.
#include <iostream>
#include <string>
int main() {
std::string name;
std::cout << "Name:\n";
if (!std::getline(std::cin, name) || name.empty()) {
std::cout << "Name is required.\n";
return 1;
}
int age = 0;
std::cout << "Age:\n";
if (!(std::cin >> age)) {
std::cout << "Age must be an integer.\n";
return 1;
}
if (age < 0 || age > 130) {
std::cout << "Age must be between 0 and 130.\n";
return 1;
}
std::string greeting = "Hello, " + name + "!";
std::cout << greeting << '\n';
std::cout << "Bytes: " << name.size() << '\n';
std::cout << "Age: " << age << '\n';
return 0;
}Enter exactly two lines, pressing Enter after each:
Le Minh An
18The program writes the following; exclude any input echoed by your terminal:
Name:
Age:
Hello, Le Minh An!
Bytes: 10
Age: 185. Common mistakes
Using
>>for a full name: only its first word is stored in the name variable.Using failed input, or retrying forever while the stream remains in a failed state.
Expecting
std::wsto keep empty lines and leading spaces: it discards them.Treating
size()as a Unicode character count, or expectingempty()to reject spaces.Assuming successful integer extraction is sufficient: range and leftovers still matter.
6. Practice
Change the sample name to
Anand age to0; expectBytes: 2,Age: 0.Keep the name
Anand try ages130,131,-1, andabc. Only130is accepted; the others report an error without printing a greeting.Try empty input and input ending after the name line. The program must stop, without looping forever or printing information from an unread number.
Enter a Vietnamese name with accents. Observe the byte count; do not interpret it as a visible-character count. Print
greetinga second time without changingname.
7. Self-check
Why is
getlinesuitable forLe Minh An? Answer: it retains spaces within a line, whereas>>reads a single word.Why does the program check the age twice? Answer: first it checks whether integer extraction succeeded; then it checks whether the integer is in the permitted range.
Does
std::wspreserve an empty line after numeric input? Answer: no. It skips all leading whitespace, potentially across several lines. To preserve line boundaries, usegetlinefor each line and parse the number.
Sample code
Source file
cpp98_foundation/06_strings_io/main.cpp
#include <iostream>
#include <string>
int main() {
std::string name;
std::cout << "Name:\n";
if (!std::getline(std::cin, name) || name.empty()) {
std::cout << "Name is required.\n";
return 1;
}
int age = 0;
std::cout << "Age:\n";
if (!(std::cin >> age)) {
std::cout << "Age must be an integer.\n";
return 1;
}
if (age < 0 || age > 130) {
std::cout << "Age must be between 0 and 130.\n";
return 1;
}
std::string greeting = "Hello, " + name + "!";
std::cout << greeting << '\n';
std::cout << "Bytes: " << name.size() << '\n';
std::cout << "Age: " << age << '\n';
return 0;
}