繁体   English   中英

如何在C ++中加入strcpy

[英]How to join strcpy in C++

我很困惑,在我的C ++编码中,请帮助我。

#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();
}

我想要像这样的输出/结果程序

Move  =  h1+h2;

您应该使用strcat连接字符串

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

使用strcat(move,h2); 添加moveh2变量的内容

strcpy(move, h1);
strcat(move,h2);   // make sure `move` have enough space to concatenate  `h1` and `h2`

首先,它会更好地使用C函数fgets代替C function gets ,因为最后是不安全的,可以覆盖内存..

例如

fgets( h1, 80, stdin );

但是无论如何,最好使用标准的C ++函数getline

如果要获取结果为Move = h1 + h2,则应检查Move是否可以容纳字符串串联h1 + h2

所以你可以写

if ( strlen( h1 ) + strlen( h2 ) < 80 )
{
    strcat( strcpy( move, h1 ), h2 );
    cout<<"Result = "<<move;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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