How to use for each loop in c++

 {Code}

#include <cstdlib>
#include <iostream>
#include <string>

using namespace std;

int main() {
string str("hello world!");
for (auto &c : str)
c = toupper(c);
cout << str;
return 0;
}

This c++ code does not compile. Error msg: main.cpp:21: error: a function-definition is not allowed here before ':' token Question: 
Is there a for each loop in c++ (range for loop?)? what is wrong with the for each loop above?

 

You need to be a member of Virtual Academy of Pakistan to add comments!

Join Virtual Academy of Pakistan

Email me when people reply –

Replies

  • IT/CS/SE Admin

    below is working C++ ver 17 code foreach

    #include <iostream>
    using namespace std;

    int main()
    {
    int arr[] = { 10, 20, 30, 40 };

    for (int x : arr)
    cout<<x<<" ";


    }

This reply was deleted.