无法将字符串复制到字符数组

时间:2018-04-16 11:58:37

标签: c++ arrays string class setter

#include<iostream>
class ravi
{
    private:
        char a[10],char b[10];
public:
    void setdata(char x[10],char y[10])
    {
        a = x; b = y;
    }
    void show()
    {
        std::cout << a << b;
    }
};
int main()
{
    ravi r;
    r.setdata("text","copied");
    r.show();
}

我正在尝试复制字符串&#34; text&#34; &#34;复制&#34;到x和y,我得到一个错误,#char;从char *到char&#34;的分配不兼容。有人告诉我我的代码有什么问题。

3 个答案:

答案 0 :(得分:7)

C ++中的字符串是std::string。您正在使用字符数组,即C字符串,NUL终止字符串等,这些字符串更难操作。

只需替换ab的类型(以及对setdata的参数的微小改进,您就可以获得一些有用的功能,以及string的一些有用功能:

#include <string>
class ravi
{
    std::string a;
    std::string b;
public:
    void setdata(const char* x, const char* y)
    {
        a = x;
        b = y;
    }

    void show()
    {
        std::cout << a << b;
    }
};

如果可以(关于ravi的API),请尝试使用std::string const&代替const char*

void setdata(std::string const& x, std::string const& y)

使用C ++ 17,您最好使用std::string_view代替const char*参数类型:

void setdata(std::string_view x, std::string_view y)

答案 1 :(得分:3)

数组没有复制赋值运算符。所以这些陈述

a=x;b=y;

无效。

您应该使用标头strcpy中声明的标准C函数strncpy<cstring>来复制字符数组。 C ++中的字符串文字也有常量字符数组的类型。因此,应使用限定符setdata声明成员函数const的参数。

void setdata( const char x[], const char y[] )
{
    strncpy( a, x, sizeof( a ) );
    a[sizeof( a ) - 1] = '\0';

    strncpy( b, x, sizeof( b ) );
    b[sizeof( b ) - 1] = '\0';
}

考虑到此声明无效

char a[10],char b[10];

要么你应该写

char a[10]; char b[10];

char a[10], b[10];

答案 2 :(得分:0)

使用strcpy中的string.h功能:

#include <string.h>

void setdata(char x[10],char y[10])
{
    strcpy(a,x);
    strcpy(b,y);
}