Hi,

I doing some exercises of the book "Deitel How to Program, 5", and in the exercise 4.27 i need to write a program that get a binary integer from user, then print it in decimal, but i can only use the programming techniques that i have learned in the book, here is a shell script that i have written to do it, if i write this in c++ i will be done.

``````#!/bin/sh

binary=\$1
numberOfChars="`echo \$binary |wc -c`"
counter="1"
decimal="0"

while [ \$counter -lt \$numberOfChars ]
do

if [ `echo \$binary |cut -c \$counter` -lt 0 ] || [ `echo \$binary |cut -c \$counter` -gt 1 ]
then

echo "A Binary number contains only 0s e 1s."

exit 0

fi

decimal=`expr \$decimal \* 2 + \`echo \$binary |cut -c \$counter\` `

counter=`expr \$counter + 1`

done

echo "Decimal: \$decimal"

exit 0``````

The problem is that in C++ i don't know how can i use something like "cut", there is a hint in the book, saying that i can use module and division operators to get the digits, but i only know how to do it with a predetermined number of digits.

Obs: Please, i cannot use "for", and i can only use the iostream and string libs.

>>i don't know how can i use something like "cut",
There is no such term.

It's pretty easy to get the digits

``````int x = 123;
int digit;
while(x > 0)
{
digit = x % 10;
x /= 10;
}``````

I'm a little confuse...Do you want a program that will take an inputted binary number and then produce its decimal equivalent?

e.g.

enter a binary number->111
ans->7

Is that what you want?

I'm a little confuse...Do you want a program that will take an inputted binary number and then produce its decimal equivalent?
Yes

It's pretty easy to get the digits
Thanks, this is what i was looking for.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.19 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.