简体   繁体   中英

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

I am a beginer learning Data Structures and Algorithms. I was trying this:

#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;
}

but the compiler is showing the following error:

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

I have used cout << many times, but never faced this error.

Contrary to your intuition, std::stack::pop() doesn't return anything ( void ). https://en.cppreference.com/w/cpp/container/stack/pop and void cannot be printed.

You probably want this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM