C++ - Strings: User Input

Overview

Estimated time: 10–15 minutes

Read words and whole lines from std::cin and understand common pitfalls.

Learning Objectives

  • Use operator>> to read a token and std::getline to read a full line.
  • Handle leftover newlines when mixing numeric and string input.

Prerequisites

Examples

#include <string>
#include <iostream>
int main(){
  std::string first, line;
  std::cin >> first;            // reads up to whitespace
  std::getline(std::cin, line); // reads the rest of the line (might be empty)
  if(line.empty()) std::getline(std::cin, line); // read the next non-empty line
  std::cout << first << "|" << line;
}

Common Pitfalls

  • After reading an int with operator>>, call std::cin.ignore() before std::getline to discard the trailing newline.