When I run it the program will repeatively rewrite everything when I type 'y'.

Really? Weird. It doesn't do anything of the sort when I run it. Mind you, what it doesn't do is clear the screen, since I removed all the <conio.h>-related function calls (the compiler I was using doesn't have any equivalent to that), which may be what you are actually noticing.

Loking at your code, you still haven't written the octal and hex conversions correctly; instead, what you are reading the value into a variable as a long value, then after some ineffective 'conversion', you are printing that same variable out as a decimal, without changing anything. You are not actually converting anything in your code; the scanf() and printf() functions are doing the conversions. This does not actually fulfill the requirements of the project, at least not as I understand it.

As for the default case, it is not necessary to have one, but it is best to handle all possible cases, so I would have kept it in.

BTW, you are still using void main(). Please, please, please fix that.

Ok sir I try to fix it. I'll just post if something is wrong.Whats wrong with my octal and hex I thought it was right because when I run the program the conversion is correct. Sir If I have this in an array what should I add in my program. Turbo C++ codes only.

I am sorry to keep bring this up, but you still haven't answered my question about wether you are supposed to be learning C++ or C. It is a very important distinction, as it would (among other things) explain why your professor isn't allowing the C++ iostreams.

C++ sir. She will allowed anything as long on what she taught on us. She is a very strict teacher. That's why almost of the student doesn't like her and Im very unfurtunate to be in her class :(

Sir heres my program now this now a functioning program. How to fix the <double enter> I only need to enter onces to enter in a loop.

#include<conio.h>
#include<stdio.h>
#include<math.h>

char value;
char key;

void Binary2Decimal();
void Octal2Decimal();
void Hexa2Decimal();

void Binary2Decimal()
       {
       gotoxy(1,13);printf("[BINARY TO DECIMAL CONVERSION]");

       int bin2,f2=1,d2=0;
       gotoxy(1,15);printf("Enter a Binary number: ");
       scanf("%d", &bin2);

       printf("\n");

       while(bin2>0)
       {
       if((bin2%10)==1)
       {
       d2=d2+f2;
       }
       bin2=bin2/10;
       f2=f2*2;
       }
       printf("Decimal equivalent is: %d", d2);
       }

void Octal2Decimal()
       {
       gotoxy(1,13);printf("[OCTAL TO DECIMAL CONVERSION]");

       long oct8,dec8,rem8,i8,sum8;
       gotoxy(1,15);printf("Enter an Octal number: ");
       scanf("%o", &oct8);

       printf("\n");

       {
       rem8=dec8%8;
       sum8=sum8 + (i8*rem8);
       }
       printf("Decimal equivalent is: %d", oct8);
       }

void Hexa2Decimal()
       {
       gotoxy(1,13);printf("[HEXADECIMAL TO DECIMAL CONVERSION]");

       long hex16,dec16,rem16,i16,sum16;
       gotoxy(1,15);printf("Enter a Hexadecimal number: ");
       scanf("%X", &hex16);

       printf("\n");

       {
       rem16=dec16%16;
       sum16=sum16 + (i16*rem16);
       }
       printf("Decimal equivalent is: %d", hex16);
       }

    int  main()
     {
      do{
       clrscr();
       gotoxy(1,1);printf("Said A. Sayre Jr");
       gotoxy(1,3);printf("Conversion from any base to base 10");
       gotoxy(1,5);printf("a - Binary");
       gotoxy(1,6);printf("b - Octal");
       gotoxy(1,7);printf("c - Hexadecimal");
       gotoxy(1,11);printf("Select a value to be converted: ");
       scanf("%c", &value);

       switch(value){
       case 'a':
       Binary2Decimal();
       break;
       case 'b':
       Octal2Decimal();
       break;
       case 'c':
       Hexa2Decimal();
       break;

       }

       gotoxy(1,20);printf("Press <DOUBLE ENTER> to Continue or Press <ANY KEY> to Exit ");
       key=getch();
       }

       while(key == 13);
       return 0;
       }

Ok ... this uses fgets ... (it's just an edited alternate version -> for your added benefit <- of the clean coding, already supplied to you, by Dani Virtuoso ... Schol-R-LEA),

(since you REALLY SHOULD learn how to use fgets ... as well as scanf and fscanf ... if you wish to do input in C++ ... but, NEED there, to use a C style of input!)

Note: here two often annoying problems with fgets get fixed.

  1. the returned string is always trimmed of any '\n' char at the end
  2. if the buffer size used for fgets was too small, the rest of that line is 'flushed' / 'discarded'

This example also features

-> input validation

and

-> re-use of a function, with a passed in const C string prompt, to facilitate getting user C string input.
(Note: the static C string 'buffer' used inside and returned, after it is used, by that function.)

/*  Note: using C style coding here ...
    so that program can be compiled with a C++  
    OR 
    a C compiler */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

#define BUFSIZE 80

#define MENU "*** CONVERSION FROM ANY BASE TO BASE 10 ***\n\n" \
             "b - Binary\n" \
             "o - Octal\n" \
             "h - Hexadecimal\n\n" \
             "Enter your choice "


/* function prototypes */

/* NOTE: uses/returns a 'static C string buffer' inside
         buffer is length BUFSIZE ... so max len of
         C string returned is BUFSIZE - 1

   NOTE: 'fixes fgets' !!! */
char* takeInString( const char prompt[] );

/* returns 1 if 's' is valid, otherwise returns 0 */
int isvalid( const char* s, size_t maxlen, unsigned int base );

unsigned long string2long( const char* rep, unsigned int base) ;
unsigned long binary2Decimal();
unsigned long octal2Decimal();
unsigned long hexa2Decimal();


unsigned long string2long( const char* rep, unsigned int base )
{
    int len, i, digit;
    unsigned long sum = 0;

    len = strlen(rep);
    for (i = 0; i < len; ++i)
    {
        /* take the ASCII value of the digit
        and subtract it by the ASCII value of '0' */
        if( rep[i] <= '9' ) digit = rep[i] - '0';
        else digit = toupper(rep[i]) - 'A' + 10;
        sum = sum*base + digit;

        /* can remove this next line, after all debugged */
        printf( "Sum so far = %lu\n", sum );
    }
    return sum;
}

unsigned long binary2Decimal()
{
    unsigned long result;
    int valid = 0;

    printf( "\n[BINARY TO DECIMAL CONVERSION]\n" );

    do
    {
        char* str = takeInString( "Enter a Binary Number "
                            "(max of 32 binary bits):  " );
        valid = isvalid( str, 32, 2 );

        if( valid )
        {
            result = string2long( str, 2 );
        }
    }
    while( !valid );

    return result;
}

unsigned long octal2Decimal()
{
    unsigned long result;
    int valid = 0;

    printf( "\n[OCTAL TO DECIMAL CONVERSION]\n" );

    do
    {
        char* str = takeInString( "Enter an Octal Number "
                            "(max entry 7777777777777777):  " );
        valid = isvalid( str, 16, 8 );

        if( valid )
        {
            result = string2long( str, 8 );
        }
    }
    while( !valid );

    return result;
}

unsigned long hexa2Decimal()
{
    unsigned long result;
    int valid  = 0;

    printf( "\n[HEXADECIMAL TO DECIMAL CONVERSION]\n" );

    do
    {
        char* str = takeInString( "Enter a Hexadecimal "
                            "Number (max entry ffffffff):  " );
        valid = isvalid( str, 8, 16 );

        if( valid )
        {
            result = string2long( str, 16 );
        }
    }
    while( !valid );

    return result;
}

char* takeInString( const char prompt[] )
{
    static char buf[BUFSIZE];
    char *p;

    printf( "%s", prompt );
    fflush( stdin );

    fgets( buf, BUFSIZE, stdin );

    /* example of a way to fix fgets TWO, 
       sometimes very annoying, problems */
    p = strchr( buf, '\n' );
    if( p ) *p = 0; /* strip off '\n' at end ... if it exists */
    else while( getchar() != '\n' ) ; /* 'flush' stdin ... */

    return buf;
}

int isvalid( const char* s, size_t maxlen, unsigned int base )
{
    /* char bot = '0'; */
    char top;
    size_t len = strlen(s);
    if( len > maxlen )
    {

        printf( "\nONLY %d char's MAXIMUM ... "
                "permitted here!\n", maxlen );
        return 0;
    }
    else if( len == 0 )
    {
        fputs( "\nYou MUST enter something here ...\n",
                stdout );
        return 0;
    }


    if( base <= 10 )
    {
        top = '0' + base-1;
        int i;
        for( i = strlen(s)-1; i >= 0; --i )
            if( s[i] > top || s[i] < '0' ) break;

        if( i == -1 ) return 1;
    }
    else
    {
        char digit;
        top = 'A' + base-11;
        int i;
        for( i = strlen(s)-1; i >= 0; --i )
        {
            digit = toupper( s[i] );
            if( digit < '0' || digit > top  ||  (digit > '9' && digit < 'A') )
                break;
        }

        if( i == -1 ) return 1;
    }

    /* if reach here ... */
    printf( "\nInvalid input here ... Try again.\n" );
    return 0;
}



int main()
{
    char* str;
    unsigned long result;

    do
    {

        int okToPrint = 1;

        printf( MENU );
        str =  takeInString( "(b, o or h):  " );

        switch( tolower(str[0]) )
        {
        case 'b': case 'B':
            result = binary2Decimal();
            break;
        case 'o': case 'O':
            result = octal2Decimal();
            break;
        case 'h': case 'H':
            result = hexa2Decimal();
            break;
        default:
            printf( "\nThe choice '%c' is not "
                    "implemented here ... try again.\n", 
                    tolower(str[0]) );
            okToPrint = 0;
        }

        if( okToPrint)
            printf( "\nDecimal equivalent is: %lu\n", result );

        str = takeInString( "\nMore numbers to convert (y/n) ?  " );
    }
    while( tolower(str[0]) != 'n' && printf( "\n" ) );

    return 0;
}

Oops ... just noticed above, don't need to take tolower in the switch ... as added both lower and upper cases ... so that now each selection has two cases that select for it.

See updated 'main' below ...

int main()
{
    char* str;
    unsigned long result;

    do
    {
        int okToPrint = 1;

        printf( MENU );
        str =  takeInString( "(b, o or h):  " );

        switch( str[0] ) // changed from above code
        {
        case 'b': case 'B':
            result = binary2Decimal();
            break;
        case 'o': case 'O':
            result = octal2Decimal();
            break;
        case 'h': case 'H':
            result = hexa2Decimal();
            break;
        default:
            printf( "\nThe choice '%c' is not "
                    "implemented here ... try again.\n", 
                    str[0] ) ;
            okToPrint = 0;
        }

        if( okToPrint)
            printf( "\nDecimal equivalent is: %lu\n", result );

        str = takeInString( "\nMore numbers to convert (y/n) ?  " );
    }
    while( tolower(str[0]) != 'n' && printf( "\n" ) );

    return 0;
}

Whats wrong with my octal and hex I thought it was right because when I run the program the conversion is correct

To illustrate what is going on with the two functions in question, I propose you try the following test: comment out the lines between the scanf() and printf() calls in Octal2Decimal(), then compile and run the program to see what happens.

void Octal2Decimal()
{
    gotoxy(1,13);printf("[OCTAL TO DECIMAL CONVERSION]");

    long oct8,dec8,rem8,i8,sum8;
    gotoxy(1,15);printf("Enter an Octal number: ");
    scanf("%o", &oct8);
/*
    printf("\n");

    {
        rem8=dec8%8;
        sum8=sum8 + (i8*rem8);
    }
*/     
    printf("Decimal equivalent is: %d", oct8);
}

What I expect you will find is that it still appears to work, even without the 'conversion' code.

Now, if you look at the code in question, you'll see that it does not even reference oct8, nor does it change it; the entire section of code has no effect on the behavior of the program! The conversion is being done by scanf(), not by your code.

The solution, as stated earlier, is to have a char array at least large enough to hold the maximum size of a 32-bit value in the representation being used (11 digits for octal, 8 for hex, plus one for the zero delimiter), and read the value into that buffer rather than directly into a long.

void Octal2Decimal()
{
    char oct8[12];
    unsigned long dec8,i8,sum8,len8;

    gotoxy(1,13);printf("[OCTAL TO DECIMAL CONVERSION]");
    gotoxy(1,15);printf("Enter an Octal number: ");
    scanf("%11s", oct8);
    printf("\n");

    len8 = strlen(oct8);
    while (i8 = 0; i8 < len8; ++i8)
    {
        dec8 = oct8[i8] - '0';  /* get the value of the digit */
        sum8 = (sum8 * 8) + dec8;
    }
    printf("Decimal equivalent is: %d", sum8);
}

That should now do the conversion correctly. Mind you, I still recommend using fgets() instead of scanf(), but it sounds like you are in a bind in that regard.

On another issue: you'll notice that my identation is different from yours in a crucial respect: I am indenting one level - four spaces - even time I have a block of code that is inside a loop or an if statement. This practice, called 'nesting', is very important. The goal of formatting code is to make the nesting levels explicit in the layout of the program. While in C++, it is purely for the benefit of the programmer, it should make reading and editing the code easier, which is why it is important to get into the habit as soon as you can. I recommend reading this article on the subject for further clarification.

Now, as thhis Wikipedia entry explains, there are several different styles which one can use to indent their code; what is important is not the specific style, but consistency in applying your chosen style. As long as you follow the main rule - indent inside a block, de-dent after the end of a block - you should be able to use the style you are comfortable with, **so long as you are consistent in appyling it*. those two rules are the real key; as long as your code makes the nesting express, and you don't change styles in the middle of a program, your good.

Fortunately, there exist several editors and styling programs that will format code automatically for you. I recommend AStyle as a simple one you can download and run on your computer. By default, it formats to Allman Style with an indent of four, but it is configurable to several different styles. If you download Code::Blocks, it includes AStyle as a plugin which can be called from the editor.

@Schol-R-LEA ... thanks for the AStyle indenting link.

Just for the fun of it, I revised my above version that used fgets ... so that it NOW ... ONLY USES SCANF, instead.

One possible student benefit, if this feature is wanted, is that using scanf, for string input, will NOT accept an empty line. Just pressing enter will not work there.

Note: the above could be a liability in some situations, as well as the inability of scanf, for string input, to get a whole line with embedded white-spaces.

But scanf is great to parse a line of words / tokens.

@john.kane.100483 ... this example may be more to your liking ?

/* convert3_uses_scanf.cpp */

/* Note: this version uses scanf, (instead of fgets) ... */
/* Note: string input using scanf ...
         waits ...
         ... for something to be entered */

#include <stdio.h>
#include <string.h>
#include <ctype.h> /* re. tolower ... */

#define BUF_SIZE 80

#define MENU "*** CONVERSION FROM YOUR CHOICE OF BASE " \
             "TO BASE 10 ***\n\n" \
             "b - Binary\n" \
             "o - Octal\n" \
             "h - Hexadecimal\n\n" \
             "Enter your choice "

void fflushStdin()
{
    char c;
    while( scanf( "%c", &c) && c != '\n' ) ;
}
int takeInChar( const char* msg )
{
    char chr;
    printf( msg );
    fflush( stdout );
    scanf( "%c", &chr );
    if( chr != '\n' ) fflushStdin();
    return chr;
}

int more() /* defaults to 'yes'/'1' ... unless 'n' or 'N' entered */
{
    if( tolower( takeInChar( "More (y/n) ? " )) == 'n' )
        return 0;
    /* else ... if you reach  here ... */
    return 1;
}

/* Uses scanf to get buffer input of upto maxStrLen ... */
/* NOTE: returns static buffer ... */
char* takeInStr( const char* msg, unsigned maxStrLen )
{
    const unsigned bufLen = BUF_SIZE;
    static char buf[bufLen];
    unsigned len = 0;

    if( maxStrLen < bufLen )
    {
        /* on example of a C 'forever loop' ...
           until break from loop or return from function */
        for( ; ; )
        {
            printf( msg );
            fflush( stdout );
            scanf( "%79s", buf ); /* adjust if change BUF_SIZE */
            fflushStdin();

            len = strlen( buf );
            if( len <= maxStrLen )
                return buf;
            /* else ... Ireach here ... */

            printf( "\nError! myMax input string length here "
                    "is %d char's long ...\n"
                    "but your string was %d char's long.\n",
                    maxStrLen, len );
        }
    }
    /* else ... if reach here ... */
    printf( "\nERROR!  The bufLen of %d needs to be "
            "greater than %d\n", bufLen, maxStrLen );
    return NULL;
}

/* returns 1 if 's' is valid, otherwise returns 0 */
int isvalid( const char* s, unsigned int base )
{
    /* char bot = '0'; */
    char top;

    if( base <= 10 )
    {
        top = '0' + base-1;
        int i;
        for( i = strlen(s)-1; i >= 0; --i )
            if( s[i] > top || s[i] < '0' ) break;

        if( i == -1 ) return 1;
    }
    else
    {
        char digit;
        top = 'A' + base-11;
        int i;
        for( i = strlen(s)-1; i >= 0; --i )
        {
            digit = toupper( s[i] );
            if( digit < '0' || digit > top  ||  (digit > '9' && digit < 'A') )
                break;
        }

        if( i == -1 ) return 1;
    }

    /* if reach here ... */
    printf( "\nInvalid input here ... Try again.\n" );
    return 0;
}

unsigned long string2long( const char* rep, unsigned int base )
{
    int len, i, digit;
    unsigned long sum = 0;

    len = strlen(rep);
    for( i = 0; i < len; ++i )
    {
        /* take the ASCII value of the digit
        and subtract it by the ASCII value of '0' */
        if( rep[i] <= '9' ) digit = rep[i] - '0';
        else digit = toupper(rep[i]) - 'A' + 10;
        sum = sum*base + digit;

        /* can remove this next line, after all debugged */
        printf( "Sum so far = %lu\n", sum );
    }
    return sum;
}

unsigned long binary2Decimal()
{
    unsigned long result;
    int valid;

    printf( "\n[BINARY TO DECIMAL CONVERSION]\n" );

    do
    {
        char* str = takeInStr( "Enter a Binary Number "
                               "(max of 32 binary bits):  ", 32 );
        valid = isvalid( str, 2 );

        if( valid )
        {
            result = string2long( str, 2 );
        }
    }
    while( !valid );

    return result;
}

unsigned long octal2Decimal()
{
    unsigned long result;
    int valid;

    printf( "\n[OCTAL TO DECIMAL CONVERSION]\n" );

    do
    {
        char* str = takeInStr( "Enter an Octal Number "
                               "(max entry 7777777777777777):  ", 16 );
        valid = isvalid( str, 8 );

        if( valid )
        {
            result = string2long( str, 8 );
        }
    }
    while( !valid );

    return result;
}

unsigned long hexa2Decimal()
{
    unsigned long result;
    int valid;

    printf( "\n[HEXADECIMAL TO DECIMAL CONVERSION]\n" );

    do
    {
        char* str = takeInStr( "Enter a Hexadecimal "
                               "Number (max entry ffffffff):  ", 8 );
        valid = isvalid( str, 16 );

        if( valid )
        {
            result = string2long( str, 16 );
        }
    }
    while( !valid );

    return result;
}




int main()
{
    unsigned long result;
    char choice;
    do
    {
        int okToPrint = 1;

        printf( MENU );
        choice =  takeInChar( "(b, o or h):  " );

        switch( choice )
        {
        case 'b': case 'B':
            result = binary2Decimal();
            break;
        case 'o': case 'O':
            result = octal2Decimal();
            break;
        case 'h': case 'H':
            result = hexa2Decimal();
            break;
        default:
            if( choice == '\n' ) choice = 0;
            printf( "\nThe choice '%c' is not "
                    "implemented here ... try again.\n",
                    choice ) ;
            okToPrint = 0;
        }

        if( okToPrint)
            printf( "\nDecimal equivalent is: %lu\n", result );

        choice = takeInChar( "\nMore numbers to convert (y/n) ?  " );
    }
    while( tolower(choice) != 'n' && printf( "\n" ) );

    return 0;;
}

Thank you for this codes sir. But I present this to my prof she reject it because she did not taught this stuff to us.

When I compile your source codes my turbo c++ compiler won't accept their are to many syntax error.

Here is my 'OLD Borland' Turbo compiler output ...

(after I removed the initial assignment of a 0 value ... that 'Turbo' didn't appreciate ... but ... it only issued a warning.)

C:\Borland\myfiles>bcc32 convert3_uses_scanf.cpp
Borland C++ 5.5.1 for Win32 Copyright (c) 1993, 2000 Borland
convert3_uses_scanf.cpp:
Turbo Incremental Link 5.00 Copyright (c) 1997, 2000 Borland

C:\Borland\myfiles>pause
Press any key to continue .

You can see ... it compiled error and warning free.

(What were you errors?)

Here is where I edited (out) the assignent of the initial zero value ...

/* Uses scanf to get buffer input of upto maxStrLen ... */
/* NOTE: returns static buffer ... */
char* takeInStr( const char* msg, unsigned maxStrLen )
{
    const unsigned bufLen = BUF_SIZE;
    static char buf[bufLen];
    unsigned len; /*** was: unsigned len = 0; ***/

    if( maxStrLen < bufLen )
    {
        /* on example of a C 'forever loop' ...
           until break from loop or return from function */
        for( ; ; )
        {
            printf( msg );
            fflush( stdout );
            scanf( "%79s", buf ); /* adjust if change BUF_SIZE */
            fflushStdin();

            len = strlen( buf );
            if( len <= maxStrLen )
                return buf;
            /* else ... Ireach here ... */

            printf( "\nError! myMax input string length here "
                    "is %d char's long ...\n"
                    "but your string was %d char's long.\n",
                    maxStrLen, len );
        }
    }
    /* else ... if reach here ... */
    printf( "\nERROR!  The bufLen of %d needs to be "
            "greater than %d\n", bufLen, maxStrLen );
    return NULL;
}

The example is not for you to hand in 'as is' ...

It was designed for your enrichment :)

The code just uses scanf (not fgets or getchar ... to illustrate the differences and similarities ... where they exist.)

If you 'see' what that code is doing ... as it 'runs' ... you should be able to strip away parts that were added to validate input, etc... (BUT ... some type of validating input is part of any 'crash proof code' ... which you SHOULD be taught ... the sooner ... the better ... as it will ease your frustrations and allow your enjoyment of programming ... programs that actually do the job you want ... and without 'crashing'.)

But leave in the parts that deal with the problem of "left over '\n' char" ... if you wish the program to work correctly ... and code it bottom up with all your own well choosen descriptive variable names, and liberal comments ... to aid in design and recall of what is supposed to happen ... at each step.

Write your code ... bottom up ... in steps ... and keep a back-up copy of each step that compiles and gives the expected output ... do NOT move on to the next step until your code ... at each step ... compiles and gives the exact expected output.

This way ... you will KNOW that any new (compiling) errors are localized to the new (small block of code added after the last 'step') ... and can ALways start over from that 'last working step' ... and start coding fresh ... if you can not find the added 'bugs'.

Be a part of the DaniWeb community

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