Concatenate strings/chars in a loop.

Please support our C++ advertiser: Intel Parallel Studio Home
Reply

Join Date: Jul 2009
Posts: 8
Reputation: Anon17 is on a distinguished road 
Solved Threads: 0
Anon17 Anon17 is offline Offline
Newbie Poster

Concatenate strings/chars in a loop.

 
1
  #1
Jul 27th, 2009
Hi there.

I have an encryption method which handles a string char by char and converts it to base 32, then adds it onto the result string. However, it seems to completely replace the result string instead of adding onto the end of it. My code:

  1. char *encrypt(std::string input, std::string key) {
  2. char* result;
  3. int lenIn = input.length();
  4. int lenKey = key.length();
  5. int i = 0;
  6. int numKey;
  7. while (i < lenIn) {
  8. numKey = charCodeAt(key, i % lenKey);
  9. long n = long(charCodeAt(input, i) + numKey);
  10. ltostr(n, base32, 32);
  11. if (i = 0) {
  12. //Cannot concatenate a blank char* it seems
  13. result = base32;
  14. } else {
  15. char* tempresult = result;
  16. sprintf(result,"%s%s",tempresult,base32);
  17. }
  18. i++;
  19. }
  20. return result;
  21. }

charCodeAt simply gets the unicode number in int format of the character entered. Can anyone help out?
Reply With Quote Quick reply to this message  
Join Date: Dec 2005
Posts: 5,850
Reputation: Salem has a reputation beyond repute Salem has a reputation beyond repute Salem has a reputation beyond repute Salem has a reputation beyond repute Salem has a reputation beyond repute Salem has a reputation beyond repute Salem has a reputation beyond repute Salem has a reputation beyond repute Salem has a reputation beyond repute Salem has a reputation beyond repute Salem has a reputation beyond repute 
Solved Threads: 749
Team Colleague
Salem's Avatar
Salem Salem is offline Offline
Void main'ers are DOOMed

Re: Concatenate strings/chars in a loop.

 
0
  #2
Jul 27th, 2009
> char* result;
This is an uninitialised pointer!
Result - you're scribbling characters all over someone else's memory - and they're not going to be happy about it.

You're already using std::string, so carry on using std::string for everything else in your program.
Reply With Quote Quick reply to this message  
Join Date: Jul 2009
Posts: 8
Reputation: Anon17 is on a distinguished road 
Solved Threads: 0
Anon17 Anon17 is offline Offline
Newbie Poster

Re: Concatenate strings/chars in a loop.

 
0
  #3
Jul 27th, 2009
Cheers, it worked perfectly when I did that.
Reply With Quote Quick reply to this message  
Reply

This thread is more than three months old.
Perhaps start a new thread instead?
Message:


Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC