简体   繁体   中英

How to join strcpy in C++

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;

You should use strcat to concatenate strings

strcpy(move, h1);
strcat(move, h2);
cout<<"Result = "<<move;
#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;
}
#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();
}

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`

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM