How to fix error: no match for 'operator<<' (operand types are 'std::ostream {aka std::basic_ostream<char>}' and 'void') while using strings and stack

How to fix error: no match for 'operator<<' (operand types are 'std::ostream {aka std::basic_ostream<char>}' and 'void') while using strings and stack

我是一名学习数据结构和算法的初学者。 我正在尝试这个:

#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() 没有 return 任何东西 (void)。 https://en.cppreference.com/w/cpp/container/stack/popvoid 无法打印。

你可能想要这个:

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