Click here to Skip to main content
14,971,029 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I run this program on compiler and it returned me the following error:


Could not convert 'stack.std::stack<wchar_t>::pop() from void to bool.

What shall i do?
C++
#include <string>
#include <stack>
#include <iostream>
using namespace std;

class CheckNumbers
{
public:
	virtual void check(const std::wstring &s)
	{
		std::stack<wchar_t> stack = std::stack<wchar_t>();
		int l = s.length();
		int zeroCounts = 0;
		int onesCounts = 0;
		for (int i = 0;i < l;i++)
		{
			stack.push(s[i]);
		}
		while (!stack.empty())
		{
			if (stack.pop()! == L'0')
			{
				zeroCounts++;
			}
			else
			{
				onesCounts++;
			}
		}
		if (zeroCounts > onesCounts)
		{
			std::wcout << std::wstring(L" 0 occurs most frequently by ") << (zeroCounts - onesCounts) << std::endl;
		}
		else if (zeroCounts < onesCounts)
		{
			std::wcout << std::wstring(L" 1 occurs most frequently by ") << (onesCounts - zeroCounts) << std::endl;
		}
		else
		{
			std::wcout << std::wstring(L" 1 and 0 both occur equal") << std::endl;
		}
	}
};
// Main method class to call the method of CheckNumbers class
class Test
{

	static void main(std::wstring args[])
	{
		(new CheckNumbers())->check(L"010100111");
	}
};


What I have tried:

I never came across any such errors and i'm rather new to C++
Posted
Updated 3-Nov-20 3:41am
v2
Comments
Joe Woodbury 3-Nov-20 16:19pm
   
Small point:

class Test
{
static void main(std::wstring args[])
{
(new CheckNumbers())->check(L"010100111");
}
};

Appears to be C#-like. It leaks. In this case, I suggest declaring an instance of CheckNumbers and call the method.

For std::stack<wchar_t> stack = std::stack<wchar_t>(); drop what's from the equal sign to the semi-colon.

The push loop could be done:

for (wchar_t ch : s)
{
stack.push(ch);
}

1 solution

The pop() function has void as return type, so it cant be casted to a bool.
You need to redesign your code:
C++
while (!stack.empty())
{
	if (stack.top() == L'0')//use of top
	{
		zeroCounts++;
	}
	else
	{
		onesCounts++;
	}
	stack.pop();//now pop
}
   
Comments
CPallini 3-Nov-20 8:07am
   
5.
Richard MacCutchan 3-Nov-20 9:41am
   
Where is it trying to convert void stack.pop() to a bool?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900