Home > database >  How to concatenate two strings
How to concatenate two strings

Time:11-16

The program is suppose to take two inputted strings, concatenate them, then print. This is the code I have right now and am wondering how to go about this. I'm still new so bear with me. Thanks in adavance.

.586
.MODEL FLAT
.STACK 4096

INCLUDE io.h

.DATA
Inputstr BYTE 100 DUP (?)
Inputstr2 BYTE 100 DUP (?)
Outputstr BYTE 100 DUP (?)
prompt BYTE "Enter a string", 0
displayLbl BYTE "Concatinated string", 0

.CODE
_MainProc PROC

input prompt, Inputstr, 100
lea esi, Inputstr
lea edi, Outputstr
push esi
push edi
cld

input prompt, Inputstr2, 100
lea esi, Inputstr2
lea edi, Outputstr
push esi
push edi
cld


whileNoNul:
cmp BYTE PTR [esi], 0
je endWhileNoNul
movsb
loop whileNoNul

endWhileNoNul:
mov BYTE PTR [edi], 0
pop esi
pop edi
output displayLbl, Outputstr

mov eax, 0
ret

_MainProc ENDP
END

My code is only printing my second output which is Inputstr2. It is suppose to print out both Inputstr and Inputstr2 together. Thanks

CodePudding user response:

I'm no assembly expert, but it looks like you're pushing data on register esi and edi twice, first for InputStr and then for InputStr2 - so won't the pop esi and pop edi have only the InputStr2 in it when the code executes the While?

CodePudding user response:

Some fine points

If you are going to allow the user to input 2 strings of up to 99 characters each, then your program should define an Outputstr that is bigger than 100.

For a concatenation between string1 and string2, you would normally place the string1 before the string2. Your code currently begins by copying string2 (and forgets to deal with string1).

The stack needs balancing: what you push also needs to come off! And just as important, you need to pop the registers in reverse order.

The loop instruction in loop whileNoNul depends on the ECX register. Your code did not prepare that register beforehand, so results will not be correct.

A solution

There's nothing that needs pushing or popping here. First copy the Inputstr1 without its terminating zero, then copy the Inputstr2 with its terminating zero. And of course, in between you don't tamper with the EDI register!

  Inputstr1 BYTE 100 DUP (?)
  Inputstr2 BYTE 100 DUP (?)
  Outputstr BYTE 200 DUP (?)

  ...

  input prompt, Inputstr1, 100
  input prompt, Inputstr2, 100

  mov  esi, OFFSET Inputstr1
  mov  edi, OFFSET Outputstr
  cld

  jmp  while
contWhile:
  stosb
while:
  lodsb
  cmp  al, 0
  jne  contWhile

  mov  esi, OFFSET Inputstr2
until:
  lodsb
  stosb
  cmp  al, 0
  jne  until

  output displayLbl, Outputstr
  • Related