[英]What is the return type of stack.top() and stack.pop() using stack<string> in cpp?
我正在尝试使用堆栈的printf()打印stack.top()的返回值,但它给出了格式不匹配的信息。 代码如下:
int main(){
stack <string> cards;
char *ch1;
char ch2[20];
cards.push("Ace");
cards.push("King");
cards.push("Queen");
cards.push("Jack");
printf("Number of cards : %ld \n", cards.size());
ch1 = cards.top(); // As sizeof(cards.top()) is 8. error of type conversion
strcpy(ch2,cards.top()); // cannot convert ‘std::basic_string<char>’ to ‘const char*’
printf("Top of the Stack : %s \n", ch);
return 0
}
在所有示例中,我都看到它是使用“ cout”打印的。
std :: string是与char*
不同的类型,以下操作无效:
ch1 = cards.top(); // top() returns a string, not a char*
我建议为您的代码使用std::string
:
int main(){
stack <string> cards;
string ch1; // std::strings
string ch2;
...
ch1 = cards.top(); // Correct
printf("Top of the Stack : %s \n", ch1.c_str()); // c_str() needed
return 0;
}
还要注意,使用printf
需要char*
类型,您可以使用std::string::c_str()
获得一个,或者(甚至更好)可以首先使用cout
:
std::cout << "Top of the Stack : " << ch1;
因此,我建议您执行以下操作:
#include <iostream>
#include <stack>
#include <string>
int main() {
std::stack <std::string> cards;
std::string ch1;
cards.push("Ace");
cards.push("King");
cards.push("Queen");
cards.push("Jack in the Jack");
std::cout << "Number of cards : " << cards.size() << std::endl;
ch1 = cards.top(); // Get the top card
std::cout << "Top of the Stack : " << ch1;
}
pop
的返回值是void
, top
返回对堆栈保存的数据类型的引用。 std::string
与char
数组不同,它不能直接与任何C字符串函数一起使用。 您可以使用std::string::c_str()
获取原始数据,但最好保留在STL范围内。 您可以使用std::cout
直接打印std::string
。
您不能使用strcpy
,它是C样式char *
字符串的C函数,对于C ++ std::string
s-如果出于某种原因必须使用C字符串,请更改:
strcpy(ch2,cards.top());
至
strcpy(ch2,cards.top().c_str());
^^^^^^^^
这将使用cards.top()
返回的std::string
,并返回一个const char *
,可以由strcpy
。
不过,更好的解决方案是始终坚持使用C ++习惯用法,即,出于显示目的,仅使用std::string
并使用std::cout
而不是printf
。
在下一行
ch1 = cards.top();
stack<string>::top()
返回string
,而ch1是char *
。 没有从string
到char *
类型转换。 要进行转换,请使用成员函数c_str
:
ch1 = cards.top().c_str();
ch1必须是const char*
,而不是char *
,因为那是c_str
返回的内容。
为什么返回const char*
? 因为否则您可以通过提取char *
并更改它来破坏字符串值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.