在函数中连接两个字符,并在 C++ 中返回输出
concatenating two chars in functions and return for output in c++
这是我的程序中的一个问题。
我必须写一个扑克游戏,我必须展示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 结尾的字符串。
此外,该程序会泄漏内存,因为您没有delete
str_Suit
也没有str_Digit
,也没有std::free
strcat
的结果。
相关文章:
- 如何读取单个字符并在输入两个字符序列时输出? 使用 while 循环和C++
- 如何在不知道对应关系的情况下在字符串中搜索字符并将其分配给另一个字符?
- 在函数中连接两个字符,并在 C++ 中返回输出
- 我正在尝试创建一个布尔函数,该函数计算字符并在字符为"()*-+"时返回 true
- 通过字符串迭代并将每个循环中的先前字符组合在一起
- 键入特殊字符并保存在文件中
- 如何将无符号简短转换为无符号字符并将值存储在字符串中
- 从文件C 读取并在需要时编写新的行字符
- 检索字符串的第一个字符,并在C++中按字母顺序进行比较
- 生成唯一的随机字符并将其保存在数组中
- 尝试在字符串中索引字符并创建新字符串
- 如何在C++中获取子字符串并在字符串之间添加字符
- 似乎无法让字符数组离开函数并在 main 中使用
- 删除字符并在字符串(C )的末端附加它们
- 如何获取输入文件的行的第二个和最后一个字符,并在C++中组成数组
- 降低字符串字符,并在转换的大写字母前添加一个_
- 我使用构造函数(使用内存 Dinamic char *t = 新字符 [10] t = "test123456" ;))时遇到错误堆错误并在析构函数中删除 [] t;错误
- 将我的字符保持在范围内,并处理它
- 由字符将字符串作为输入字符,并在按回车键时给出输出
- 使用c++,在制作控制台应用程序时,是否有一种方法可以让cin接受输入的下一个字符并在不按回车键的情况下继续