Convert between base system in C on Linux

Click For Summary

Discussion Overview

The discussion revolves around a C programming issue related to converting numbers between different base systems (decimal, hexadecimal, octal) on a Linux platform. Participants are addressing a problem where the program does not correctly prompt for the output base after entering the input number.

Discussion Character

  • Technical explanation
  • Debate/contested

Main Points Raised

  • One participant describes their code and the issue where the program fails to allow input for the output base after entering the number.
  • Another participant suggests improving code readability through proper indentation and the use of debugging tools to trace execution steps.
  • A third participant agrees on the readability issue and provides tips on using code tags for better formatting, as well as warnings about potential problems with array indexing in the context of HTML rendering.
  • A participant explains that the problem with input arises from the newline character left in the input buffer after entering the number, which interferes with subsequent input for the output base.
  • Suggestions are made to use `getchar()` to consume the newline character or to flush the input buffer using `fflush(stdin)` to resolve the input issue.

Areas of Agreement / Disagreement

Participants generally agree on the readability issues of the posted code and the cause of the input problem, but there is no consensus on the best approach to handle the input buffer issue, as different methods are suggested.

Contextual Notes

There are unresolved aspects regarding the use of `fflush(stdin)`, as its behavior can be implementation-defined and may not be portable across different compilers or systems.

ParticleGinger6
Messages
32
Reaction score
5
Homework Statement
Your program should convert an integer into another base. The input integer could be in decimal, octal or hexadecimal. The output could be converted into any of the bases. A sample run is below. The user’s response is in boldface.

Base of input integer: Enter d for decimal, h for hexadecimal or o for octal: d
Enter the number: 178
Enter the base of the output (d, h or o): h
The integer 178 in decimal is b2 in hexadecimal
Do you wish to do another? (Y or N): Y

Base of input integer: Enter d for decimal, h for hexadecimal or o for octal: o
Enter the number: 423
Enter the base of the output: d
The integer 423 in octal is 275 in decimal
Do you wish to do another? (Y or N): N
Relevant Equations
Dec to Hex/Oct: divide by the wanted base till the remainder is greater than the dividen.
We have been requested to run this on linux. I am able to read in the original base system and then I am able to enter the number. As soon as I enter the original number the system reads out "Enter the base of the output:" then does not allow the user to enter the second base. Instead it just prints "Do you wish to do another". I have a scanf running for the second base however, it seems to not be wanting to scan anything in.

C:
#include <stdio.h>
#include <string.h>
#include <math.h>

int main(){
    int num, res, j, k;
    long long int n;
    char base1, base2, hex[100];
    char ch;
    do{
        printf("\nBase of input integer: ");
        printf("\nEnter d for decimal, h for hexadecimal or o for octal: ");
        scanf("%c", &base1);
        switch(base1){
            case 'd': printf("\nEnter the number: ");
                            scanf("%d", &num);
                            printf("\nEnter the base of the output (d,h,o): ");
                            scanf("%c", &base2);
                            switch(base2){
                               case 'o': printf("\nOctal Value: ");
                                              decconversion(num, 8);
                                              printf("The decimal value %d in Octal value is %d",num,remainder);
                                              break;
                              case 'h': printf("\nHexadecimal value: ");
                                              decconversion(num, 16);
                                              break;
                            }
                        break;
        case 'h': printf("\nEnter the number: ");
                        scanf("%s", hex);
                        printf("Enter the base of the output (d,h,o): ");
                        scanf("%c", &base2);
                        switch(base2){
                            case 'd': printf("\nDecimal Value: %d",HexToDec(hex));
                                           break;
                            case 'o': printf("\nOctal Value: %d", HexToOct(hex));
                                           break;
                        }
        case 'o': printf("\nEnter the number: ");
                        scanf("%lld", &n);
                        printf("\nEnter the base of the output (d,h,o): ");
                        scanf("%c", &base2);
                        switch(base2){
                            case 'd': printf("\nDecimal Value: %d", OctToDec(n));
                                            break;
                            case 'h': printf("\nHexadecimal Value: %d", decconversion((OctToDec(n)), 16));
                                            break;
                        }
                        break;
            break;
        }
        printf("\nDo you wish to do another Y/N: ");
        scanf("%c", &ch);
    }
    while(ch=='y' || ch == 'Y');
    return 0;
}

int decconversion(int num, int base){
    int remainder = num%base;
    if(num==0){
        return;
    }
    decconversion(num/base,base);
    if(remainder <10){
        printf("%d", remainder);
    }
    else {
        printf("%c", remainder - 10+'A');
    }
}

int HexToOct(char hex[]){
    int i, len, dec = 0, oct =0;
    for(len=0;hex[len]!='\0'; len++);
    for(i=0; hex[ i]!='\0'; i++, len--){
        if(hex[ i]>='0' & hex[ i]<='9'){
            dec =dec+(hex[ i]-87)*pow(16, len-1);
        }
    }
    i =1;
    while(dec!=0){
    oct = oct +(dec%8)*i;
    dec = dec/8;
    i = i*10;
    }
    return oct;
}

int HexToDec(char* hex){
    int dec =0, base = 1, i, d;
    char c;
    i = strlen(hex)-1;
    while(i>=0){
        c = *(hex+i);
        if(c>='A' && c<='F')
            d = 10+c-'A';
        else if(c>='a' && c<='f')
            d = 10+c-'a';
        else
            d = c-'0';
        dec +=d*base;
        base*=16;
        i--;
    }
    return dec;
}

int OctToDec(int oct){
    int dec = 0, base =1;
    int t;
    t = oct;
    while(t>0){
        dec+=(t%10)*base;
        t/=10;
        base*=8;
    }
    return dec;
}
 
Last edited by a moderator:
Physics news on Phys.org
Your posted code is too hard to follow.
1) You should use levels of indentation to make it clear where the nested {} sections begin and end. If you have that in the code, use the code option to post it correctly.
2) You can use the debugger to go step-by-step through an execution. That will tell you exactly where things go wrong. There is a learning curve to using the debugger that is well worth the effort. Barring that, a few printed "I am on line ##" should help you to narrow down the problem.
 
FactChecker said:
Your posted code is too hard to follow.
Agree. I have enclosed the code with code tags, and have attempted to indent to make it more readable. @ParticleGinger6, please use code tags -- there is a brief description in the first article of this forum section.

Also, be cautious when using an array index i. An expression such as hex[ i], will cause problems unless there is an added space before i. The reason for this is that browsers will interpret an i in brackets as a cue to render everything that follows in italics.
For a similar reason, you shouldn't use b in brackets as an array index -- the browser will turn everything that follows into bold.
 
Last edited:
  • Like
Likes   Reactions: FactChecker
ParticleGinger6 said:
As soon as I enter the original number the system reads out "Enter the base of the output:" then does not allow the user to enter the second base. Instead it just prints "Do you wish to do another". I have a scanf running for the second base however, it seems to not be wanting to scan anything in.
In your code, you ask the user to enter a character for the base of the input (d, o, or h), then the number, and finally a character for the base of the output. The reason your code doesn't let you enter the character for the output base is that when you enter the number (in the 2nd scanf call), the input buffer contains the characters for the number, plus the newline character produced by hitting the Enter key.

The newline character can't be part of the number, so it sits in the input buffer, ready for the next call to scanf. On the third call to scanf for the base for the result, base2 gets set with the newline character, and your program doesn't let you do any input.

One thing that you could do is to call getchar() after the 2nd scanf call, to consume the newline character. Another thing you could do is to flush the input buffer, using this code:fflush(stdin);
You don't need to add any more #include files -- fflush and getchar() are declared in stdio.h, and stdin, the standard input stream, is declared in a header that stdio.h includes.
 
  • Like
Likes   Reactions: FactChecker

Similar threads

  • · Replies 19 ·
Replies
19
Views
3K
  • · Replies 1 ·
Replies
1
Views
11K
  • · Replies 17 ·
Replies
17
Views
3K
  • · Replies 4 ·
Replies
4
Views
2K
  • · Replies 1 ·
Replies
1
Views
5K
  • · Replies 1 ·
Replies
1
Views
3K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 12 ·
Replies
12
Views
3K
  • · Replies 4 ·
Replies
4
Views
8K
  • · Replies 1 ·
Replies
1
Views
2K