I have stumbled upon an exercise on Michael Dawson's book: Beginning C++ Game Programming. It asks to find what is wrong with the following code. I think it is the <= operator, but i have my doubts. Any ideas? Here is the code:
1 2
for (int i = 0; i <= phrase.size(); ++i)
cout << “Character at position “ << i << “ is: “ << phrase[i] << endl;
Yes, the size() function gives the number of elements in that array, since arrays count from 0 and not 1, there will be no n'th element for an array of size n.
#include <iostream>
usingnamespace std;
int count = 0, input;
int main()
{
string phrase;
cout << "Please input a phrase: " << endl;
cin >> phrase;
cout << endl << "With phrase.size() " << endl;
for (int i = 0; i <= phrase.size(); ++i)
cout << "Character at position" << i << " is: " << phrase[i] << endl;
cout << endl << "With phrase.size() - 1 " << endl ;
for (int i = 0; i <= phrase.size() - 1; i++)
cout << "Character at position" << i << " is: " << phrase[i] << endl;
return 0;
}
output..
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
Please input a phrase:
test
With phrase.size()
Character at position0 is: t
Character at position1 is: e
Character at position2 is: s
Character at position3 is: t
Character at position4 is: ?
With phrase.size() - 1
Character at position0 is: t
Character at position1 is: e
Character at position2 is: s
Character at position3 is: t