How to User input strings in C++ ?


In C++, you can use the std::string class to handle strings. To get user input for a string, you can use the std::getline() function. Here are some examples:

Example 1: Getting a single line of input from the user

#include <iostream>
#include <string>

int main() {
    std::string input;
    std::cout << "Enter a string: ";
    std::getline(std::cin, input);
    std::cout << "You entered: " << input << std::endl;
    return 0;
}

In this example, we declare a string variable input to store the user's input. We then use std::getline() to read a line of input from std::cin (which represents the standard input stream, usually the keyboard). The user's input is stored in input, and we print it out using std::cout.

Example 2: Getting multiple lines of input from the user

#include <iostream>
#include <string>

int main() {
    std::string input;
    std::cout << "Enter some text (press Ctrl+D to end):" << std::endl;
    while (std::getline(std::cin, input)) {
        std::cout << "You entered: " << input << std::endl;
    }
    return 0;
}

In this example, we use a while loop to repeatedly call std::getline() and read lines of input from the user. The loop continues until the user presses Ctrl+D (or Ctrl+Z on Windows) to signal the end of input. Each line of input is stored in input and printed out using std::cout.

Example 3: Getting input with a prompt and validation

#include <iostream>
#include <string>
#include <limits>

int main() {
    std::string input;
    int age;
    std::cout << "Enter your name: ";
    std::getline(std::cin, input);
    std::cout << "Enter your age: ";
    while (!(std::cin >> age)) {
        std::cout << "Invalid input. Please enter a number: ";
        std::cin.clear();
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    }
    std::cout << "Hello, " << input << "! You are " << age << " years old." << std::endl;
    return 0;
}

In this example, we prompt the user to enter their name and age. We use std::getline() to read the name as a string, and then use a while loop to read the age as an integer. If the user enters invalid input (i.e. something that can't be converted to an integer), we print an error message and clear the input stream using std::cin.clear() and std::cin.ignore(). Once we have valid input, we print out a greeting using std::cout. Note that we use std::numeric_limits<std::streamsize>::max() to ignore any remaining characters on the input line after the user enters invalid input.



About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.