Nick
Nick

Reputation: 9373

C++ For loop problem

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?

Upvotes: 0

Views: 333

Answers (2)

Marcelo Cantos
Marcelo Cantos

Reputation: 185852

Is ln guaranteed 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:

void User::setUserid(string ln, string id){
    userid = "0" + ln.substr(0, 6) + "0" + id.substr(id.size() - 2);
}

Note that this will produce a shorter userid if ln.size() < 6 and throw out_of_range if id.size() < 2.

Upvotes: 3

dacwe
dacwe

Reputation: 43504

The string ln might have less characters than 6 - ln[k] will be out of bounds.

Note that the code will crash if the id string contains less then two characters (i will be negative).

Upvotes: 1

Related Questions