Output not right

S

Smitsky

Why do I get (using Dev-C++) "111," when I should be getting "101" when I
enter "5?" I never get a "0" as an output. Can anyone let me know why?
Thanks. Steve

//----------------------------Code Starts------------------------------->

#include<stack>
#include<iostream>

using namespace std;

int main()
{
stack<int> s;
int number;
int digit;
cout<<"Please enter a decimal number to convert to binary.\n";
cin>>number;

while(number>0)
{
digit=number%2;
s.push(digit);
number=number/2;
}

while(!s.empty())
{
s.pop();
cout<<digit;
}

cout<<endl;

return 0;
}

//-----------------------------End Code---------------------------->
 
V

Victor Bazarov

Smitsky said:
Why do I get (using Dev-C++) "111," when I should be getting "101" when I
enter "5?" I never get a "0" as an output. Can anyone let me know why?
Thanks. Steve

//----------------------------Code Starts------------------------------->

#include<stack>
#include<iostream>

using namespace std;

int main()
{
stack<int> s;
int number;
int digit;
cout<<"Please enter a decimal number to convert to binary.\n";
cin>>number;

while(number>0)
{
digit=number%2;
s.push(digit);
number=number/2;
}

while(!s.empty())
{
s.pop();
cout<<digit;

You're printing some kind of left-over from the former processing.
Shouldn't you be printing

s.top();

(and actually _before_ you pop it) ?
 
A

Ashes

Hi Steve

You forgot to add the following statement before popping the stack in the
while loop:

digit = s.top();

It is currently displaying the value of digit as it was in the last
assignment of digit=number%2.

Regards
Ashley Visagie
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,183
Messages
2,570,967
Members
47,517
Latest member
Andres38A1

Latest Threads

Top