How come when I enter a name, for example, joey, the output is 1329? How is that even happening? I wouldn't expect the team += a[i] to give me an output like that. Thanks for taking the time to read.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <iostream>
#include <string>
usingnamespace std;
int main() {
string team = "";
string a = "Billy";
cout << "Enter name: ";
cin >> team;
for(int i = 0; i < team.size(); i++) {
if(team.find(a[i]) > a.size()) team += a[i];
}
cout << team.size() << endl;
return 0;
}
This is strange. I presume the if(team.find(a[i]) > a.size()) statement is to check if the character wasn't found. I changed it to if(team.find(a[i]) == string::npos) which is the normal way of checking if it wasn't found, and then if I enter "joey", it prints 8.
There is no range-checking in a[i], as i increases it may easily go beyond the bounds and start accessing extraneous characters from some adjacent memory locations. Meanwhile, team is getting larger and the for loop will find its upper limit increased accordingly.
I wonder that someone gets a number at all. When I enter joey it crashes with "String subscript out of range" when i == 5. Here is the code with some TRACE output.