0

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?

6
  • 1
    And what ln and id did you provide? Commented Sep 25, 2011 at 15:17
  • Do you have some way of knowing that ln is always length 6? Commented Sep 25, 2011 at 15:18
  • And if you don't comment out the first loop, what happens? What do you mean by "crashes"? Does it refuse to compile? Are there any error messages? Commented Sep 25, 2011 at 15:20
  • It crashes when last name = Adams, which is 5 characters. So I believe it has something to do with that Commented Sep 25, 2011 at 15:20
  • @DanielRHicks when I run it just popups with an error screen telling me "Debug assertion failed" and asks to abort. Commented Sep 25, 2011 at 15:22

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

5 Comments

It crashes when last name = Adams so I believe it has something to do with that
@Nick Oh you have got to be kidding!
@Konrad Sorry, I'm learning how to program. This stuff isn't immediately clear to me.
Thank you, worked perfectly and the code is much less convoluted than mine, haha :)
@Nick: No worries. Keep at it, and don't be discouraged by negative comments.
1

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).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.