I have a loop that takes two inputs, a last name and an ID, then converts it to a user id. The code looks like this:
void User::setUserid(string ln, string id){
string temp = "0";
string temp2 = "0";
for (int k = 0; k < 6; k++){
temp += ln[k];
}
for (int i = id.length()-2; i<id.length(); i++){
temp2 += id[i];
}
userid = temp+temp2;
}
For some reason if I comment out the first for loop it will compile and build. Any ideas why the code crashes?
Is
lnguaranteed to have at least six characters? You may be shooting past the end of the string.In any event, you’ve chosen a slow and complicated way to copy parts of strings around. This should suffice:
Note that this will produce a shorter userid if
ln.size() < 6and throwout_of_rangeifid.size() < 2.