for loop error in cplusplus tutorial

Write your question here.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
  // range-based for loop
#include <iostream>
#include <string>
using namespace std;

int main ()
{
  string str {"Hello!"};
  for (char c : str)
  {
    std::cout << "[" << c << "]";
  }
  std::cout << '\n';
}
Seems to run OK here.

http://coliru.stacked-crooked.com/a/86ff78f774db76d6

What compiler are you using? It needs to have C++11 support.
c++ 2010
Visual C++ 2010 is pre-C++11 so the code won't compile.
The range for loop is C++11, though, personally I prefer to do:
1
2
3
4
for(auto c : str)   // or if I want to tweak the string auto &c
{
      /* ... */
}
Last edited on
Registered users can post here. Sign in or register to post.