why does this transpire

I'm confused, someone explain? the errors are odd

1
2
3
4
5
6
7
8
#include <iostream>

int main() {
    std::string str = "hi";
    for(int i = str.begin(); i != str.end(); ++i) {
          std::cout << str[i] << '\n';
    }
}
closed account (zb0S216C)
"std::string::begin( )" returns a pointer to the very first element of a "std::string" instance. Because no integer type can be converted to an address, the compiler produces an error. What you're looking for is iterators. They can be defined like so:

1
2
3
4
5
6
int main( )
{
  std::string Str_( "Hi!\n" );
  for( std::string::iterator It_( Str_.begin( ) ); It_ < Str_.end( ); ++It_ )
    std::cout << *It_;
}

Read more here: http://www.cplusplus.com/reference/string/string/

Wazzak
Last edited on
Alternatively,
1
2
3
    for (int i = 0; i < str.size(); ++i) {
          std::cout << str[i] << '\n';
    }
so you cant use the subscript operator with pointers?
closed account (3qX21hU5)
There is no need to use a subscript with a pointer because that pointer is already pointing to that element in the string.

So when you do ++It_ you are telling to pointer to point to the next element in that string. You can also do basic arithmetic on the pointer to (like It_ += 4 which tells it to jump 4 elements forward).

But to answer your question no you cant use a subscript with a pointer I don't believe.

If you want to use a subscript on the string use std::string::size_type (Preferred) or int
Topic archived. No new replies allowed.