More help needed with basic C++ programming

justinoh

Member
Nov 15, 2001
134
0
0
Hey guys!

Need some help in C++ coding for a program to convert decimals to binary code. This is what I have come up with and I hope you guys can modify it for me.

#include <iostream>
#include <cstdlib>
#include <string>

using namespace std;

int main()
{
int value;
cout << "Enter a number: "; cin >> value;
// I will need to call dec2bin here. Not sure how to do it.
cout << value << "is" << answer << "in binary.";
system ("Pause");
return 0;
}

int dec2bin(int value)
{
string answer = "";
while (value > 0)
{
answer = answer + (value % 2);
value = value / 2;
}
reverseStr (answer);
}


I understand that I'll need an algorithm to divide the given number by 2, keep the quotient and append the remainder to a string (str). Keep dividig the quotient by 2 and append the reamainder to the string until the quotient is 0. The answer will be in reverse so I'll need to reverse the string using reverseStr.

I need to have one function called dec2bin which is already there but needs modification. This function does not write anything to the screen but returns a string which I need it to be string dec2bin (int num)

Progress of the coding should be: Get input from user in the main function, call dec2bin function and display the result.
Hope you guys can help me with this. If possible, please stick to the current code and algorithm as it is required for my exercise. Thanks everyone!
 

kleinesarschloch

Senior member
Jan 18, 2003
529
0
0
void dec2bin(int nVal, std::string& rstrOut)
{
for(unsigned int i = 0x80000000; i; i >>= 1)
{
rstrOut.insert(rstrOut.end(), nVal & i ? '1' : '0');
}
}

 

theAnimal

Diamond Member
Mar 18, 2003
3,828
23
76
A few things you need to do:

declare answer in main()

return something from dec2bin (make sure the function return type matches)

return something other than "" if zero is input

Some suggestions:

Loop a set number of times (8, 16, 32) to create binary numbers of the same length

Check input for limits

If you change answer = answer + (value % 2); to answer = (value % 2) + answer; you won't need to reverse string

 

glugglug

Diamond Member
Jun 9, 2002
5,340
1
81
string dec2bin(int value)
{
stringstream s;
s << ios::binary << value;
return s.str();
}


sorry, couldn't resist.

Your existing function should work, except answer should be the return value of int2dec or maybe a reference parameter. (no need to return int there), and you need a special case for the number 0.

Also,
answer = answer + (value % 2);
value = value / 2;

is clearer faster as this:

answer = std::string(value & 1) + answer; //note that reversing this string concatenation removes the need to reverse the string later.
value >>= 1;

or better yet replace the whole body of the function with this:

char binarystr[33];
char *startchar = binarystr+32;
*startchar = '\0';
if(value==0) //special case because otherwise 0 becomes empty string
{
*(--startchar) = '0';
}
while(value != 0)
{
*(--startchar) = '0'+(value & 1);
value >>= 1;
}
return string(startchar);
 

VBboy

Diamond Member
Nov 12, 2000
5,793
0
0
glugglug,

How about some readable code this time? ;)

*(--startchar) = '0'+(value & 1);
value >>= 1;


Whoa.
 

justinoh

Member
Nov 15, 2001
134
0
0
Thanks for all the replies guys. Really appreciate it alot. I was hoping you guys could modify the code that I've written and not make a big change over it. This is to enable me to understand my coding along the way. Also I did not really understand most of what was posted as I have not covered those in my studies. It doesn't matter if the code is long, inefficient or unecessary as what I have done but I think it is important for me to fully understand the basics first before I go on to something more complicated.

I have made very minor changes in the function dec2bin as it was the easiest for me to comprehend. As theAnimal mentioned, this is done to remove the need to reverse the string. Please help me out here guys from the current code I've posted below. I believe those lines in bold below are where I need to add/make changes. I hope someone nice enough can review the whole code I've posted below and make the necessary changes to fit the code I have written.

int main()
{
int value;
// How do I declare answer here?
cout << "Enter a number: "; cin >> value;
// How do I call dec2bin function here?
cout << value << "is" << answer << "in binary.";
system ("Pause");
return 0;
}

int dec2bin(int value)
{ string answer = "";
while (value > 0)
{
answer = (value % 2) + answer;
value = value / 2;
// How do I return string answer here?
}
}

Thanks alot guys!
 

theAnimal

Diamond Member
Mar 18, 2003
3,828
23
76
Here you are:

int main()
{
int value;
// How do I declare answer here?
string answer;
cout << "Enter a number: "; cin >> value;
// How do I call dec2bin function here?
answer = dec2bin(value);
cout << value << "is" << answer << "in binary.";
system ("Pause");
return 0;
}

string dec2bin(int value) //int dec2bin(int value)
{ string answer = "";
while (value > 0)
{
answer = (value % 2) + answer;
value = value / 2;
// How do I return string answer here?
return answer;
}
}


you still need to return something besides empty string for a "0" input value
and you should check the input for limits
 

justinoh

Member
Nov 15, 2001
134
0
0
theAnimal, thanks for your quick reply! I have made the changes however when I compile them I still get several errors. The line with errors will be in bold.

int main()
{
int value;
// How do I declare answer here?
string answer;
cout << "Enter a number: "; cin >> value;
// How do I call dec2bin function here?
answer = dec2bin(value); // Implicit declaration function of `int dec2bin(...)'
cout << value << "is" << answer << "in binary.";
system ("Pause");
return 0;
}

string dec2bin(int value) //int dec2bin(int value)
{ string answer = "";
while (value > 0)
{
answer = (value % 2) + answer; // No match for 'int + string&'
value = value / 2;
// How do I return string answer here?
return answer;
}
}

I don't understand these errors at all. As for a '0' input value, I think it should go something like this:

string dec2bin(int value)
{
string answer = "";
if (value == 0)
return // Return string here but i'm not sure how to return a string with 0
else
while (value > 0)
{
answer = (value % 2) + answer;
value = value / 2;
return answer;
}
}

Perhaps that'll work?
 

glugglug

Diamond Member
Jun 9, 2002
5,340
1
81
Originally posted by: justinoh

answer = dec2bin(value); // Implicit declaration function of `int dec2bin(...)'
dec2bin has to be declared before the code in main so that the compiler knows what it is when compiling main. Put the line:
string dec2bin(int value) ;
either on a line by itself before main or in an included header file.

answer = (value % 2) + answer; // No match for 'int + string&'
value % 2 is an int, not a string, and there is no overriden operator+ for adding a string to an int. You need to convert to string so it knows to use operator+(string,string) for concatenation, i.e. change this line to:
answer = string(value % 2) + answer;

 

Krakerjak

Senior member
Jul 23, 2001
767
0
0
This is exactly like an old assignment i had.
edited a bit to reflect your method


string dec2bin(int value);

int main()
{
int value;
string answer;

cout << "Enter a number: "; cin >> value;
answer = dec2bin(value);

cout << endl << value << " is " << answer << " in binary." << endl;

return 0;
}

string dec2bin(int value)
{
string answer("");
int msbit;
int msbitflag = 0;

for(int bit=0; bit<32; bit++)
// 32 times for 32 bits (4 bytes), ints compiler are 32 bits
// cout << sizeof(int);
// will output how many bytes an int value uses
{
msbit = value & 0x80000000;
// Isolate most significant bit

msbit = msbit / 0x80000000;
msbitflag += msbit;
// used to suppress leading zeros and for an
//error check at the end of the function

if(msbitflag != 0)
// will only start adding 1's and 0's to answer
// once it reaches the first binary "1" msbit.
// ie. instead of "00000000000000000000000000110001"
// will print "110001".

{
if(msbit == 1)
answer.append("1");
else if(msbit == 0)
answer.append("0");
else
return (answer.assign("error"));
}

value *= 2;
// Shift bits left to get next msbit
// ie. "0100" will become "1000"

}

if( (bit == 32) && (msbitflag == 0) ) // If all of the bits were = 0, just print a 0
answer.assign("0");

return answer;
}
 

theAnimal

Diamond Member
Mar 18, 2003
3,828
23
76
I don't know if you already have the zero thing fixed but just add this before return answer;

if (answer == "")
answer = "0";
 

kleinesarschloch

Senior member
Jan 18, 2003
529
0
0
it is a really bad practice to return non-trivial types (like std::string) by value. also, a function like this does not need to return any error codes.