Loading
0x10Lesson 2 of 9

Use types, strings, and input streams

Store values with clear types and read input using C++ streams.

16 min 5-question quiz 1 code exercise
By the end of this lesson you can
  • Use common built-in types, std::string, and std::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.

main.cpp · C++20
1#include <iostream>
2#include <string>
3
4int main() {
5    std::string name;
6    std::cin >> name;
7    std::cout << "Welcome, " << name << "!\n";
8}
Output
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::string for managed text.

  • >> reads tokens; getline reads 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.

Exercise 1

Echo a typed value

+25 XP

Read an integer from standard input and print You entered N followed by a newline.

  • Positive number
  • Negative number
main.c
Loading editor…

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…

Did you like the lesson? 😆👍
Consider a donation to support our work: