gpt4 book ai didi

c++ - (C++) 尝试打印出 char* 数组(我认为)

转载 作者:太空狗 更新时间:2023-10-29 21:24:29 25 4
gpt4 key购买 nike

我有这两个数组:

const char *face[] =
{"Deuce", "Three", "Four", "Five",
"Six", "Seven", "Eight", "Nine", "Ten",
"Jack", "Queen", "King", "Ace", "\0"};

const char *suit[] = { " of Hearts", " of Clubs", " of Diamonds", " of Spades", "\0" };

实际上,因为我什至不擅长 C++,我什至不知道你什么时候在你的数组中或其他地方使用星号......如果有人能解释一下,我将不胜感激......

但不管怎样,问题是我正试图打印出所有可能的牌,它们的花色是这样的:

for (int n = 0; n<strlen(*suit); n++){ //where strlen(*suit) should be 4
for(int i = 0; i<strlen(*face); i++){ //where strlen(*face) should be 13
cout << endl << face[i] << suit[n] << endl;
}
}

使用该代码,我的程序崩溃了。我究竟做错了什么? (它在使用 n<4 和 i<13 时有效,但如果我从数组中添加或删除项目,我希望它实际有效)

最佳答案

函数strlen是通过 const char* , 指向以 null 结尾的字符数组的指针。您不能使用它来计算字符串数组的长度。

相反,我建议您这样做:

const char *face[] =
{"Deuce", "Three", "Four", "Five",
"Six", "Seven", "Eight", "Nine", "Ten",
"Jack", "Queen", "King", "Ace", NULL};

因此,哨兵是空指针。像这样的循环:

for (int i=0; face[i]; i++)
// do something with face[i]

当然,对于另一个数组也是如此。


现在,综上所述,您正在以错误的方式处理 C++ 程序。

  • 不使用 C 字符串,指向字符数组的指针,而是使用 std::string .
  • 不要使用原始数组来保存字符串,而是使用标准容器类。在你的情况下你想要 std::vector<std::string> .

我能给你的最好建议是忘记 C 的做事方式,并尝试学习惯用的 C++ 方式来编写代码。

关于c++ - (C++) 尝试打印出 char* 数组(我认为),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16002731/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com