Back to course sections
    Mark As Completed Discussion

    String Input and Output

    In C++, you can read and write strings using the std::cin and std::cout objects from the iostream library.

    To read a string from the user, you can use the std::getline function. This function reads a line of input until a newline character is encountered and stores it in a string variable.

    Here's an example:

    TEXT/X-C++SRC
    1#include <iostream>
    2#include <string>
    3
    4int main() {
    5  std::string input;
    6
    7  // Read string input from the user
    8  std::cout << "Enter a string: ";
    9  std::getline(std::cin, input);
    10
    11  // Print the input string
    12  std::cout << "You entered: " << input << std::endl;
    13
    14  return 0;
    15}

    In this example, we declare a string variable input to store the user's input. We use std::getline to read a line of input from the user and store it in input. Finally, we use std::cout to print the input string.

    You can try running this program and entering a string to see the result.

    CPP
    OUTPUT
    :001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment