如何修复错误:使用字符串和堆栈时与"运算符<<"不匹配(操作数类型为"std::ostream {aka std::basic_ostream<char>}"和"void")



我是学习数据结构和算法的初学者。我试过这个:

#include<iostream>
#include<ostream>
#include<stack>
#include<string>
using namespace std;
int main (){
string original ;
string a = "";
std::stack<string> library;

cin >> original;
for(int i=1; i < original.size() -1; i++){
char b = original[i];
if(!((b == '/' ) || (b == '\' ))){
a = a + b;
}
else{
library.push(a);
a = "";
};
};
for(int j=0; j < library.size(); j++){
cout << library.pop() ;
}
return 0;
}

但编译器显示以下错误:

prog.cpp:26:14: error: no match for ‘operator<<’ (operand types are ‘std::ostream {aka std::basic_ostream<char>}’ and ‘void’)
cout << library.pop() ; 

我已经使用cout <<很多次了,但从未遇到过这个错误。

与您的直觉相反,std::stack::pop()不返回任何内容(void(。https://en.cppreference.com/w/cpp/container/stack/pop并且不能打印CCD_ 4。

你可能想要这个:

for(int j=0; j < library.size(); j++){
cout << library.top() ;
library.pop();
}

相关内容

最新更新