c++ loop through string

#include <iostream>
#include <string>

int main() {
    std::string str = "Hello, world!";

    // Loop through the string character by character
    for (char c : str) {
        // Print each character
        std::cout << c << std::endl;
    }

    return 0;
}

Explanation:

  1. #include <iostream> and #include <string>: These lines include necessary libraries for input-output operations and string handling.

  2. int main() {: This line marks the beginning of the main function, the entry point of the program.

  3. std::string str = "Hello, world!";: This declares a string variable named str and initializes it with the value "Hello, world!".

  4. for (char c : str) {: This initiates a loop that iterates through each character in the string str. It uses a range-based for loop to assign each character to the variable c.

  5. std::cout << c << std::endl;: Inside the loop, this line prints each character c followed by an end-of-line character to the standard output (console).

  6. return 0;: Marks the end of the main function and indicates successful completion of the program.