Receiving User Input Strings

To read strings from user input, you can use std::cin for single words or std::getline() for entire lines.

Using std::cin

Example: Reading a Single Word

#include <iostream>
#include <string>

int main() {
    std::string name;
    std::cout << "Enter your name: ";
    std::cin >> name;
    std::cout << "Hello, " << name << "!" << std::endl;
    return 0;
}

Using std::getline()

Example: Reading a Full Line

#include <iostream>
#include <string>

int main() {
    std::string fullName;
    std::cout << "Enter your full name: ";
    std::getline(std::cin, fullName);
    std::cout << "Hello, " << fullName << "!" << std::endl;
    return 0;
}

Key Takeaways

  • Use std::cin for single-word input.
  • Use std::getline() for multi-word input.
  • Include the <string> header when working with strings.