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:
#include <iostream>
and#include <string>
: These lines include necessary libraries for input-output operations and string handling.int main() {
: This line marks the beginning of themain
function, the entry point of the program.std::string str = "Hello, world!";
: This declares a string variable namedstr
and initializes it with the value "Hello, world!".for (char c : str) {
: This initiates a loop that iterates through each character in the stringstr
. It uses a range-based for loop to assign each character to the variablec
.std::cout << c << std::endl;
: Inside the loop, this line prints each characterc
followed by an end-of-line character to the standard output (console).return 0;
: Marks the end of themain
function and indicates successful completion of the program.