Ask coding questions

← Back to all posts
Is there a C++ equivelant to C#'s foreach loop?
DungeonMaster00 (170)

I'm working on a C++ program that will take something the user typed in and convert it to morse code. The program converts what the user typed in character by character.

However, I don't now if there is a way to do that character by character, basically a C++ equivalent to C#'s foreach loop.

Here are some code samples of what the loop would look like in other languages, one in Python and one in C#.


Python:

inventory = ["sword", "potion", "shield"]
for item in inventory:
    print(item)

C#:

string[] inventory = {"sword", "potion", "shield"};
foreach (string item in inventory) {
    Console.WriteLine(item);
}

Basically, I want to know if there's a way to do something like that in C++.

Code:

Answered by Bookie0 (5669) [earned 5 cycles]
View Answer
Comments
hotnewtop
Bookie0 (5669)

here check this out:

https://stackoverflow.com/questions/3648951/foreach-loop-in-c-equivalent-of-c-sharp

https://www.geeksforgeeks.org/g-fact-40-foreach-in-c-and-java/

but basically i think its like this:

std::array<std::string, 3> strarr = {"ram", "mohan", "sita"};
for(const std::string& str : strarr) {
  listbox.items.add(str);
}

Happy coding and hope this helps! =)

Bookie0 (5669)

cool! happy to help! ;) @nk1rwc

Coder100 (15771)

indeed there is!

for (item : arr) {
  cout << item;
}

more here

personally I think C# is better at these types of things.

Eh C++ more powerful