0
0
C++programming~10 mins

String input and output in C++ - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - String input and output
Start Program
Prompt User for Input
User Types String
Store Input in String Variable
Output the String
End Program
The program starts, asks the user to type a string, stores it, then prints it back.
Execution Sample
C++
#include <iostream>
#include <string>

int main() {
  std::string name;
  std::getline(std::cin, name);
  std::cout << name << std::endl;
  return 0;
}
This code reads a full line of text from the user and then prints it.
Execution Table
StepActionInput/ValueVariable 'name'Output
1Program starts---
2Wait for user inputUser types: Hello World--
3Store input in 'name'Hello WorldHello World-
4Print 'name'-Hello WorldHello World
5Program ends-Hello World-
💡 Program ends after printing the input string.
Variable Tracker
VariableStartAfter InputFinal
name""Hello WorldHello World
Key Moments - 2 Insights
Why do we use std::getline instead of std::cin >> name?
std::getline reads the whole line including spaces, while std::cin >> name stops at the first space. See execution_table step 2 where input has spaces.
What happens if the user just presses Enter without typing anything?
The variable 'name' becomes an empty string "". The program still prints a blank line as shown in variable_tracker.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 3, what is the value stored in 'name'?
A"Hello"
B"Hello World"
C"World"
D""
💡 Hint
Check the 'Variable name' column at step 3 in execution_table.
At which step does the program output the string?
AStep 4
BStep 3
CStep 2
DStep 5
💡 Hint
Look at the 'Output' column in execution_table.
If the user input was "Goodbye", how would 'name' change after input?
A"Hello World"
B"Good"
C"Goodbye"
D"Bye"
💡 Hint
Refer to variable_tracker and imagine replacing input with "Goodbye".
Concept Snapshot
String input and output in C++:
- Use std::string to store text.
- Use std::getline(std::cin, var) to read full line including spaces.
- Use std::cout << var << std::endl; to print the string.
- std::cin >> var reads only until first space.
- Always include <string> and <iostream> headers.
Full Transcript
This example shows how a C++ program reads a full line of text from the user using std::getline and stores it in a string variable named 'name'. Then it prints the stored string back to the screen. The execution flow starts with the program waiting for user input, then storing that input, and finally outputting it. The variable 'name' changes from empty to the user's input after reading. Using std::getline allows capturing spaces in the input, unlike std::cin >> name which stops at the first space. The program ends after printing the input string.