String Concatenation

String Concatenation

Write a program with a loop that runs 6 times.

Every time the loop runs the user should be prompted for an input.

Each input should be added to a std::string varaible using the += or + operators.

When the loop is done running, output the combined string.

Hint

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

Use getline to avoid running into problems getting inputs with spaces.

Answer

#include <iostream>
#include <string>

int main() {
    std::string combinedString;

    // Loop runs 6 times
    for (int i = 0; i < 6; ++i) {
        std::cout << "Enter input " << (i + 1) << ": ";
    	std::string input;
        std::getline(std::cin, input);  // Read user input
        combinedString += input;  // Append the input to the combined string
    }

    // Output the combined string
    std::cout << "The combined string is: " << combinedString << std::endl;
}
Questions