[英]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.