Hello.. I'm new in this forum.. I got two codes that I don't know what's the problems and I've try so many but the result displayed is still the same.. forgive me for my bad english.. I'm from Malaysia.
The first problem is about this code.
The first run is good, but when I choose to run the application again, the program automatically display 'Error!' after it display 'Base: '..Code:#include <stdio.h> #define MAXBUFFERSIZE 80 int main(){ int base; char optExit, userIn, optExitUpper; char buffer[MAXBUFFERSIZE]; //sufficient to handle one line int char_count; //number of characters read for this line do{ system("cls"); opt: printf("\n\nBase: "); userIn = getchar(); char_count = 0; while((userIn != '\n') && (char_count < MAXBUFFERSIZE)) { //avoid user from entering invalid input type buffer[char_count++] = userIn; userIn = getchar(); } buffer[char_count] = 0x00; //null terminate buffer base = atoi(buffer);//convert from char to int //example if (base == 1){ } else { printf ("Error!"); goto opt; } //option to exit printf("\n\n\nRun application again (Y/N)?"); scanf(" %c",&optExit); optExitUpper = toupper(optExit); } while (optExitUpper == 'Y'); system("pause"); return 0; }
Another question is about loop in the code below.
The last while loop didn't work perfectly. For example when I check the value of hexNum[j--] in every loops, it display FF or 3E but when I combine it and store it in arrToStr, it save as FFF or 3E3.Code:char* convBinToHex(int binNumInt){ char binNumChar[9],hexNum[9]; static char arrToStr[3]; int i=0,j=0,temp; snprintf(binNumChar, sizeof(binNumChar), "%d", binNumInt); //convert integer to char while(binNumChar[i]){ binNumChar[i] = binNumChar[i] -48; ++i; } --i; while(i-2>=0){ temp = binNumChar[i-3] *8 + binNumChar[i-2] *4 + binNumChar[i-1] *2 + binNumChar[i] ; if(temp > 9) hexNum[j++] = temp + 55; else hexNum[j++] = temp + 48; i=i-4; } if(i ==1) hexNum[j] = binNumChar[i-1] *2 +binNumChar[i] + 48 ; else if(i==0) hexNum[j] = binNumChar[i] + 48 ; else --j; strcpy(arrToStr,""); while(j>=0){ strcat(arrToStr,&hexNum[j--]); //combine all string } return arrToStr; }
How do I solve both problems? Thank you for all your help and advice.



LinkBack URL
About LinkBacks



