Use types, strings, and input streams
Store values with clear types and read input using C++ streams.
- Use common built-in types,
std::string, andstd::cin.
A type determines which values an object can hold and which operations make sense. Common types include int, double, bool, and char. Use std::string for text and include <string>. std::cin >> value reads the next whitespace-delimited token; std::getline reads a whole line, which is useful when text may contain spaces.
1#include <iostream>
2#include <string>
3
4int main() {
5 std::string name;
6 std::cin >> name;
7 std::cout << "Welcome, " << name << "!\n";
8}Input: Sam Welcome, Sam!
The example uses >>, so a name with spaces is read as only its first word. Mixing operator>> and getline requires care because the newline left in the input stream may be read immediately by getline.
Key takeaways
Choose types that communicate the kind of value.
Use
std::stringfor managed text.>>reads tokens;getlinereads a line.
Lesson quiz
5 questions · pass with 4 correct · up to 50 XP
Passing this quiz completes the lesson and keeps your streak going. Questions you miss come back in review sessions later.
Practice: write C++
Write C++20 in the editor and run it against sample input. GCC 14 compiles the code through Compiler Explorer, a free public service; your source and test input are sent there.
Echo a typed value
Read an integer from standard input and print You entered N followed by a newline.
- Positive number
- Negative number
Your code is compiled as C++20 with gcc 14 (-Wall -Wextra) and run on Compiler Explorer (godbolt.org), a free public service.
Questions about this lesson
Stuck? Ask. Figured something out? Share it. Explaining is one of the best ways to learn.
Loading posts…