在函数中连接两个字符,并在 C++ 中返回输出

concatenating two chars in functions and return for output in c++

本文关键字:字符 并在 返回 输出 两个 C++ 连接 函数      更新时间:2023-10-16

这是我的程序中的一个问题。

我必须写一个扑克游戏,我必须展示5张牌的手。

我构建了一个"卡"类和Hand类,该类提供 5 张卡片并以main显示。

所以我必须从卡类中检索花色"黑桃"和数字"4"。

"S4">

我必须检索 5 张卡片才能在main中呈现:

S4 D6 H3 D7 H9

所以我首先尝试将字符"S"和字符"4"组合在一起,从 Card 类中形成一个字符*:

char* Card::get_Property() {
char* str_Suit = new char(suit);      // Load in 'S'
char* str_Digit = new char(digit);    // Load in '4'
char* combined = { '' };
strcpy(combined, str_Suit);
strcat(combined, str_Digit);          // Should be "S4"
return combined;
}

返回的"组合应该被S4并发送到手类进行存储:

// handCards[] is the initialized Card class
const char* Hand::show() {
char* temp = { '' };
temp = handCards[0].get_Property();
for (int j = 1; j < 5; j++) {
strcat(temp, " ");
strcat(temp, handCards[j].get_Property());
}
const char* output = temp;
return output;
}

在主要将像这样调用:

Hand hand;
cout << hand.show();

但是,调试器没有组合花色和数字(都是字符(,而是说内存分配不正确,两个字符都消失了。

我尝试了许多方法并在stackoverflow上搜索,结果保持不变。

如何分配内存或其他方法来解决此问题?

您可以返回std::string。例

std::string Card::get_Property() {
return std::string(1, suit) + digit;
}

或者,如果您使用绳降:

return absl::StrCat(suit, digit);

您的尝试问题:

char* combined = { '' };

这简直是格式错误。char*不能由char初始化,因为这些类型之间没有隐式转换。

strcpy(combined, str_Suit);

行为是未定义的,因为str_Suit不指向以空结尾的字符串,这是strcpy的先决条件。

strcat(combined, str_Digit);

行为未定义,因为两个参数都不指向以 null 结尾的字符串。

此外,该程序会泄漏内存,因为您没有deletestr_Suit也没有str_Digit,也没有std::freestrcat的结果。

相关文章: