将字符串分配给结构的属性

我正在尝试初始化 main() 中的数组。但我收到一个错误。这是代码的样子:

#include<iostream>
#include<string.h>
using namespace std;

class word
{
public:
    char str[20];
};

int main()
{
    word a;
    word b;
    a.str[]="12345";
    b.str[]="67";
}

'a' 和 'b' 是类词的 2 个对象。

回答

如果您使用的是 C 字符串,则需要将其复制过来:

int main()
{
    word a;
    word b;

    strncpy(a.str, "12345", sizeof(a.str));
    strncpy(b.str, "67", sizeof(b.str));
}

如果您想更有效地使用 C++,请考虑使用std::string

#include <iostream>
#include <string>

class word
{
public:
    std::string str; // Embrace the std:: prefix, it's there for a reason
};

int main()
{
    word a;
    word b;

    a.str = "12345";
    b.str = "67";
}

现在分配非常简单。

注意:您的原始代码有语法错误,因为a.str[] = ...它不是有效的 C++。该[]部分的意思是“未知/任意长度的数组”,可以在函数签名中使用,但不能在赋值中使用。您可以这样做,a.str[n] = 'x'但这会分配一个且仅一个字符。


以上是将字符串分配给结构的属性的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>