为什么在c++中使用strcat()时,输出缺少第一个字母?

dluptydi  于 2023-04-01  发布在  其他
关注(0)|答案(2)|浏览(108)

这里我想合并两个字符数组,并把它们放到第一个字符数组中,但是当我计算第二个字符数组时,它缺少了第一个字母,为什么?

#include <bits/stdc++.h>
using namespace std;
int main() {
    
    char s1[4] = "one";
    char s2[4] = "two" ;
    
    strcat(s1, s2);
    cout << s1 << endl; //onetwo
    
    cout  << s2; // wo

    return 0;
}
nbysray5

nbysray51#

调用函数strcat时,需要将一个指针作为第一个参数传递给内存缓冲区,该缓冲区足够大,可以存储连接的字符串。
在本例中,连接的字符串长度为6个字符("onetwo"),因此内存缓冲区的大小必须至少为7个字符(包括终止空字符)。但是,在您的情况下,内存缓冲区的大小只有4个字符,这是不够的。因此,您的程序正在调用undefined behavior,这意味着任何事情都可能发生。这包括你在问题中描述的行为。
要解决此问题,必须使数组s1的长度至少为7个字符:

#include <iostream>
#include <cstring>

using namespace std;

int main() {
    
    char s1[7] = "one";
    char s2[4] = "two" ;
    
    strcat(s1, s2);

    cout << s1 << endl;    
    cout << s2 << endl;

    return 0;
}

此程序具有所需的输出:

onetwo
two
vecaoik1

vecaoik12#

在C++中,你应该使用std::string来处理字符串:

#include <iostream>
#include <string>

int main() {
    std::string s1 = "one";
    std::string s2 = "two";

    s1 += s1; // append s2 to s1

    std::cout << s1 << '\n';
    std::cout << s2 << '\n';
}
oneone
two

相关问题