String Input Parrot

String Input Parrot

Make a program that declares a std::string object and uses std::cin to assign a value to it.

Output the inputed string back to the user 10 times.

Hint

You have to include <iostream> and <string>.

Answer

#include <iostream>
#include <string>

int main() {
    std::string inputString;

    // Read string from user
    std::cout << "Enter a string: ";
    std::cin >> inputString;

    // Output the string 10 times
    for (int i = 0; i < 10; ++i) {
        std::cout << inputString << std::endl;
    }
}

Note how a input of multiple words (seperated by space) will lead to only the first word being repeated.

This due to std::cin's tendency to seperate inputs by space to allow for multiple variable assignments like this: std::cin >> input1 >> input2;. 1.8.3 discusses this further and offers getline as a solution to this.

Questions