#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?
Thanks in advance.
There is no foreach in C. You can use a for loop to loop through the data but the length needs to be know or the data needs to be terminated by a know value (eg. null).
In Java, the for-each loop is used to iterate through elements of arrays and collections (like ArrayList). It is also known as the enhanced for loop.
Notable languages without foreach are C, and C++ pre-C++11.
The code is valid, as can be demonstrated on an online compiler.
Please refer to your compiler documentation to be sure you have enabled C++11. The option is often called -std=c++11
. You might have to download an upgrade; check your package manager for GCC (currently at 4.8) or Clang (currently 3.3).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With