Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use for each loop in c++

Tags:

c++

#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.

like image 798
Ra1nWarden Avatar asked Jun 24 '13 02:06

Ra1nWarden


People also ask

Can you do a for-each loop in C?

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).

What is the use of for-each loop?

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.

Is there a foreach in C?

Notable languages without foreach are C, and C++ pre-C++11.


1 Answers

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).

like image 83
Potatoswatter Avatar answered Oct 08 '22 00:10

Potatoswatter