but I thought that there was also a way that you could use the beginning and end of the array to loop threw the array like this .
use vector and you can do what you want using iterators.
Ancient Dragon
Retired & Loving It
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
How about something like:
for( const std::string* str = myArray ; str != 0 ; str++ )
std::cout << *str << '\n';
std::cout << '\n';
~s.o.s~
Failure as a human
11,938 posts since Jun 2006
Reputation Points: 3,281
Solved Threads: 734
@ AD,
Thanks AD, but, I thought that begin and end also worked with strings no?
Iterators work only for C++ containers. String, Vector etc. are containers and iterators work well with them. Array is not a C++ container class. You can use iterator to walk through the characters of the string..@ s.o.s,
That doesn't work s.o.s, I think it's because strings are not \0 terminated.
If you will look closely, I have done "str != 0", here str is a pointer. The above code works perfectly well for me.
~s.o.s~
Failure as a human
11,938 posts since Jun 2006
Reputation Points: 3,281
Solved Threads: 734
Okay looks like something queer is going on around here. I ran the same program without any modifications and this is what I get:
January
February
March
April
May
June
July
August
September
October
November
December
Press ENTER to continue.
~s.o.s~
Failure as a human
11,938 posts since Jun 2006
Reputation Points: 3,281
Solved Threads: 734
>>for(const std::string* str = myArray ; str != 0; str++ )
Now how can that ever work because myArray is not a nulll-terminated array. You are attempting to apply C-style character array techniques to a c++ string, and won't work.
Ancient Dragon
Retired & Loving It
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
I know it was wrong and was going to edit the post but dont know why it works in my case....
Just wanted to make someone double cheked it because it works in my case( dont know how ).
Mr. Dragon, if you have a VS2005, can you please check it out because Jobe has I think got a VC6.
~s.o.s~
Failure as a human
11,938 posts since Jun 2006
Reputation Points: 3,281
Solved Threads: 734
Mr SOS -- it works up to a point -- gives the famous message box that a fatal error has occured -- similar to core dump in *nix.
Jo: There is a very simple fix to the problem -- check for an empty string
int main()
{
std::string myArray[] = { "January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December", ""};
for(const std::string* str = myArray ; *str != ""; str++ )
std::cout << *str << '\n';
std::cout << '\n';
std::cin.get();
return 0;
}
Ancient Dragon
Retired & Loving It
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343