1

im confused, in my coding C++ please help me..

#include <conio.h>
#include <string.h>
#include <iostream.h>
main()
{
    char h1[80];
    char h2[80];
    char move[80];
    clrscr();
    cout<<"Character 1 = ";
    gets(h1);
    cout<<"Character 2 = ";
    gets(h2);
    strcpy(move, h1);
    cout<<"Result = "<<move;
    getch();
}

I want output/result program like

Move  =  h1+h2;
Ridwan Syah
  • 83
  • 1
  • 2
  • 10

5 Answers5

4

You should use strcat to concatenate strings

strcpy(move, h1);
strcat(move, h2);
cout<<"Result = "<<move;
Yuriy Kolbasinskiy
  • 3,791
  • 3
  • 16
  • 33
  • 3
    I'd point out that this could cause UB since `h1`, `h2`, and `move` are all of the same size, so if eg `h1` had a length of 30 and `h2` had a length of 30 we would be writing outside `move`, but the OP is using `gets` so buffer overflow seems not to be of concern. – IllusiveBrian Oct 02 '14 at 06:44
3
#include <string>
#include <iostream>
main()
{
    std::string h1;
    std::string h2;
    std::string move;
    std::cout << "Character 1 = ";
    std::cin >> h1;
    std::cout << "Character 2 = ";
    std::cin >> h2;
    move = h1 +h2;
    std::cout << "Result = " << move;
}
TNA
  • 2,595
  • 1
  • 14
  • 19
3
#include <conio.h>
#include <string>
#include <iostream>

main()
{
    std::string h1;
    std::string h2;
    std::string move;
    clrscr();
    std::cout << "Character 1 = ";
    std::getline(std::cin, h1);
    std::cout << "Character 2 = ";
    std::getline(std::cin, h2);
    move = h1 + h2;
    std::cout << "Result = " << move;
    getch();
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
1

use strcat(move,h2); to add content of move and h2 variable

strcpy(move, h1);
strcat(move,h2);   // make sure `move` have enough space to concatenate  `h1` and `h2`
Rustam
  • 6,485
  • 1
  • 25
  • 25
0

First of all it would be better to use C function fgets instead of C function gets because the last is unsafe and can overwrite memory..

For example

fgets( h1, 80, stdin );

But in any case it would be even better to use standard C++ function getline.

If you want to get the result as Move = h1+h2 then you should check that Move can accomodate the string concatenation h1 + h2

So you could write

if ( strlen( h1 ) + strlen( h2 ) < 80 )
{
    strcat( strcpy( move, h1 ), h2 );
    cout<<"Result = "<<move;
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335